This is page 1 of 2. Use http://codebase.md/shannonlal/mcp-linear?lines=true&page={x} to view the full context.
# Directory Structure
```
├── .eslintrc.json
├── .github
│ ├── dependabot.yml
│ ├── pull_request_template.md
│ └── workflows
│ └── ci.yml
├── .gitignore
├── .husky
│ └── pre-commit
├── .npmignore
├── package.json
├── pnpm-lock.yaml
├── prompts
│ ├── CODING_STANDARDS.md
│ ├── LINEAR_API_REFERENCE_DOCS.md
│ ├── MCP_REFERENCE_DOCS.md
│ └── STEP_1_INITIAL_ANALYSIS.md
├── README.md
├── src
│ └── server
│ ├── index.ts
│ └── requests
│ ├── getTicketsRequestHandler.test.ts
│ └── getTicketsRequestHandler.ts
├── tsconfig.json
├── tsconfig.test.json
└── vitest.config.ts
```
# Files
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
```
1 | node_modules
2 | build/
3 |
```
--------------------------------------------------------------------------------
/.npmignore:
--------------------------------------------------------------------------------
```
1 | # Source files
2 | src/
3 | example/
4 | test/
5 |
6 | # Configuration files
7 | .eslintrc.json
8 | tsconfig.json
9 | tsconfig.test.json
10 | vitest.config.ts
11 |
12 | # Development files
13 | .husky/
14 | .github/
15 | prompts/
16 |
17 | # Documentation
18 | docs/
19 | *.md
20 | !README.md
21 |
22 | # Git files
23 | .git/
24 | .gitignore
25 |
26 | # IDE files
27 | .vscode/
28 | .idea/
29 |
30 | # Test coverage
31 | coverage/
32 |
33 | # Lock files
34 | pnpm-lock.yaml
35 |
```
--------------------------------------------------------------------------------
/.eslintrc.json:
--------------------------------------------------------------------------------
```json
1 | {
2 | "env": {
3 | "node": true,
4 | "es2022": true
5 | },
6 | "extends": [
7 | "eslint:recommended",
8 | "plugin:@typescript-eslint/recommended",
9 | "plugin:@typescript-eslint/recommended-requiring-type-checking",
10 | "prettier"
11 | ],
12 | "parser": "@typescript-eslint/parser",
13 | "parserOptions": {
14 | "ecmaVersion": "latest",
15 | "sourceType": "module",
16 | "project": ["./tsconfig.json", "./tsconfig.test.json"]
17 | },
18 | "plugins": ["@typescript-eslint"],
19 | "rules": {
20 | "@typescript-eslint/explicit-function-return-type": "error",
21 | "@typescript-eslint/no-unused-vars": ["error", { "argsIgnorePattern": "^_" }],
22 | "@typescript-eslint/no-explicit-any": "error",
23 | "@typescript-eslint/no-floating-promises": "error",
24 | "@typescript-eslint/no-misused-promises": ["error", {
25 | "checksVoidReturn": {
26 | "arguments": false
27 | }
28 | }],
29 | "no-console": ["error", { "allow": ["warn", "error"] }],
30 | "@typescript-eslint/require-await": "warn"
31 | },
32 | "ignorePatterns": ["build/", "coverage/", "*.js"]
33 | }
34 |
```
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
```markdown
1 | The following is the README for the MCP Linear Project. This will be a project which
2 |
```
--------------------------------------------------------------------------------
/prompts/CODING_STANDARDS.md:
--------------------------------------------------------------------------------
```markdown
1 |
```
--------------------------------------------------------------------------------
/tsconfig.test.json:
--------------------------------------------------------------------------------
```json
1 | {
2 | "extends": "./tsconfig.json",
3 | "compilerOptions": {
4 | "rootDir": "."
5 | },
6 | "include": ["test/**/*", "vitest.config.ts", "src/**/*.test.ts"],
7 | "exclude": ["node_modules", "build"]
8 | }
9 |
```
--------------------------------------------------------------------------------
/.github/dependabot.yml:
--------------------------------------------------------------------------------
```yaml
1 | version: 2
2 | updates:
3 | - package-ecosystem: "npm"
4 | directory: "/"
5 | schedule:
6 | interval: "weekly"
7 | versioning-strategy: "auto"
8 | labels:
9 | - "dependencies"
10 | - "npm"
11 | commit-message:
12 | prefix: "chore"
13 | include: "scope"
14 |
```
--------------------------------------------------------------------------------
/vitest.config.ts:
--------------------------------------------------------------------------------
```typescript
1 | import { defineConfig } from "vitest/config";
2 |
3 | export default defineConfig({
4 | test: {
5 | globals: true,
6 | environment: "node",
7 | include: ["src/**/*.test.ts"],
8 | coverage: {
9 | provider: "v8",
10 | reporter: ["text", "json", "html"],
11 | exclude: [
12 | "node_modules/**",
13 | "build/**",
14 | "test/**",
15 | "**/*.test.ts",
16 | "vitest.config.ts",
17 | ],
18 | },
19 | },
20 | });
21 |
```
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
```json
1 | {
2 | "compilerOptions": {
3 | "target": "ES2022",
4 | "module": "ESNext",
5 | "moduleResolution": "Bundler",
6 | "outDir": "./build",
7 | "rootDir": "./src/server",
8 | "strict": true,
9 | "esModuleInterop": true,
10 | "skipLibCheck": true,
11 | "forceConsistentCasingInFileNames": true,
12 | "declaration": true,
13 | "sourceMap": true
14 | },
15 | "include": ["src/server/**/*.ts"],
16 | "exclude": ["node_modules", "build", "test", "**/*.test.ts"]
17 | }
18 |
```
--------------------------------------------------------------------------------
/.github/workflows/ci.yml:
--------------------------------------------------------------------------------
```yaml
1 | name: CI
2 | run-name: ${{ github.actor }} triggered CI workflow
3 | on:
4 | pull_request:
5 |
6 | jobs:
7 | main:
8 | name: Lint and Test
9 | runs-on: ubuntu-latest
10 | steps:
11 | - name: Checkout
12 | uses: actions/checkout@v4
13 |
14 | - name: Setup PNPM
15 | uses: pnpm/action-setup@v4
16 | with:
17 | version: 8.15.4
18 |
19 | - name: Setup Node.js
20 | uses: actions/setup-node@v4
21 | with:
22 | node-version: "18.19.0"
23 | cache: "pnpm"
24 | cache-dependency-path: "pnpm-lock.yaml"
25 |
26 | - name: Verify lockfile
27 | run: |
28 | if [ ! -f "pnpm-lock.yaml" ]; then
29 | echo "pnpm-lock.yaml not found!"
30 | exit 1
31 | fi
32 | echo "pnpm-lock.yaml found"
33 | cat pnpm-lock.yaml
34 |
35 | - name: Install dependencies
36 | run: pnpm install
37 |
38 | - name: Run ESLint
39 | run: pnpm lint
40 |
```
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
```json
1 | {
2 | "name": "mcp-linear",
3 | "version": "0.0.1",
4 | "description": "",
5 | "main": "build/index.js",
6 | "type": "module",
7 | "bin": {
8 | "mcp-postman": "./build/index.js"
9 | },
10 | "scripts": {
11 | "build": "tsc && chmod +x build/index.js",
12 | "clean": "rm -rf build",
13 | "lint": "eslint . --ext .ts",
14 | "format": "prettier --write \"src/**/*.ts\"",
15 | "prepare": "husky",
16 | "test": "vitest"
17 | },
18 | "keywords": [
19 | "mcp",
20 | "linear"
21 | ],
22 | "author": "",
23 | "license": "ISC",
24 | "dependencies": {
25 | "@linear/sdk": "^37.0.0",
26 | "@modelcontextprotocol/sdk": "^1.0.4",
27 | "dotenv": "^10.0.0"
28 | },
29 | "lint-staged": {
30 | "*.{js,jsx,ts,tsx}": [
31 | "prettier --write",
32 | "eslint --fix"
33 | ],
34 | "*.{json,md,yml,yaml}": [
35 | "prettier --write"
36 | ]
37 | },
38 | "devDependencies": {
39 | "@types/node": "^22.10.4",
40 | "@typescript-eslint/eslint-plugin": "^6.0.0",
41 | "@typescript-eslint/parser": "^6.0.0",
42 | "@vitest/coverage-v8": "^1.0.0",
43 | "axios": "^1.7.9",
44 | "cross-env": "^7.0.3",
45 | "eslint": "^8.0.0",
46 | "eslint-config-prettier": "^9.0.0",
47 | "husky": "^9.1.7",
48 | "lint-staged": "^15.3.0",
49 | "prettier": "^3.4.2",
50 | "ts-node": "^10.9.2",
51 | "typescript": "^5.7.2",
52 | "vitest": "^2.1.8"
53 | }
54 | }
55 |
```
--------------------------------------------------------------------------------
/.github/pull_request_template.md:
--------------------------------------------------------------------------------
```markdown
1 | ### Task List
2 |
3 | - [ ] You have included a description of the PR
4 | - [ ] You have included code examples or test cases demonstrating your changes
5 | - [ ] All linting checks are passing
6 | - [ ] All tests are passing
7 | - [ ] You have completed local testing with Postman collections
8 | - [ ] Documentation has been updated (if applicable)
9 |
10 | ### Description
11 |
12 | _A few sentences describing the overall effects and goals of the pull request._
13 | _What is the current behavior, and what is the updated/expected behavior with this PR?_
14 |
15 | ### Testing Notes
16 |
17 | _(Required) Provide information about how to test this PR properly. Include:_
18 |
19 | - _Steps to test locally with example Postman collections_
20 | - _Any specific MCP server configuration needed_
21 | - _Expected outputs or behaviors to verify_
22 | - _For complex changes, include a Loom video demonstrating the functionality_
23 |
24 | ### Example Usage
25 |
26 | ```typescript
27 | // Include code examples showing how to use your changes
28 | // For example, how to use new MCP tools or resources you've added
29 | ```
30 |
31 | ### Test Results
32 |
33 | ```
34 | // Include relevant test output or screenshots showing tests passing
35 | ```
36 |
37 | ### Additional Context
38 |
39 | _Include any additional context, screenshots, or references that would help reviewers understand your changes._
40 |
```
--------------------------------------------------------------------------------
/src/server/requests/getTicketsRequestHandler.ts:
--------------------------------------------------------------------------------
```typescript
1 | import { LinearClient } from "@linear/sdk";
2 | import { McpError, ErrorCode } from "@modelcontextprotocol/sdk/types.js";
3 |
4 | export interface GetTicketsArgs {
5 | apiKey: string;
6 | status?: "active" | "completed" | "canceled";
7 | limit?: number;
8 | }
9 |
10 | export async function handleRequest(
11 | args: GetTicketsArgs,
12 | ): Promise<{ content: Array<{ type: string; text: string }> }> {
13 | try {
14 | // Validate arguments
15 | if (!args.apiKey) {
16 | throw new McpError(ErrorCode.InvalidParams, "API key is required");
17 | }
18 |
19 | // Initialize Linear client
20 | const linearClient = new LinearClient({
21 | apiKey: args.apiKey,
22 | });
23 |
24 | // Get authenticated user
25 | const me = await linearClient.viewer;
26 |
27 | // Build query options
28 | const queryOptions: Record<string, unknown> = {
29 | first: args.limit || 10,
30 | };
31 |
32 | if (args.status) {
33 | queryOptions.filter = {
34 | state: {
35 | type: {
36 | eq: args.status,
37 | },
38 | },
39 | };
40 | }
41 |
42 | // Get user's assigned issues
43 | const issues = await me.assignedIssues(queryOptions);
44 |
45 | if (!issues.nodes.length) {
46 | return {
47 | content: [
48 | {
49 | type: "text",
50 | text: "No tickets found matching the criteria.",
51 | },
52 | ],
53 | };
54 | }
55 |
56 | // Format the issues
57 | const formattedIssues = await Promise.all(
58 | issues.nodes.map(async (issue) => {
59 | const state = await issue.state;
60 | return {
61 | id: issue.id,
62 | title: issue.title,
63 | status: state?.name || "Unknown",
64 | priority: issue.priority,
65 | url: issue.url,
66 | createdAt: issue.createdAt,
67 | };
68 | }),
69 | );
70 |
71 | return {
72 | content: [
73 | {
74 | type: "text",
75 | text: JSON.stringify(formattedIssues, null, 2),
76 | },
77 | ],
78 | };
79 | } catch (error) {
80 | if (error instanceof McpError) {
81 | throw error;
82 | }
83 |
84 | throw new McpError(
85 | ErrorCode.InternalError,
86 | `Failed to fetch Linear tickets: ${error instanceof Error ? error.message : "Unknown error"}`,
87 | );
88 | }
89 | }
90 |
```
--------------------------------------------------------------------------------
/src/server/index.ts:
--------------------------------------------------------------------------------
```typescript
1 | #!/usr/bin/env node
2 | import { Server } from "@modelcontextprotocol/sdk/server/index.js";
3 | import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
4 | import {
5 | CallToolRequestSchema,
6 | ListToolsRequestSchema,
7 | McpError,
8 | ErrorCode,
9 | } from "@modelcontextprotocol/sdk/types.js";
10 |
11 | declare const process: NodeJS.Process;
12 |
13 | class LinearMcpServer {
14 | private server: Server;
15 |
16 | constructor() {
17 | this.server = new Server(
18 | {
19 | name: "linear-mcp-server",
20 | version: "0.1.0",
21 | },
22 | {
23 | capabilities: {
24 | tools: {},
25 | },
26 | },
27 | );
28 |
29 | this.setupTools();
30 | }
31 |
32 | private setupTools(): void {
33 | // Define available tools
34 | this.server.setRequestHandler(ListToolsRequestSchema, () => ({
35 | tools: [
36 | {
37 | name: "get-linear-tickets",
38 | description: "Get tickets from Linear API for the authenticated user",
39 | inputSchema: {
40 | type: "object",
41 | properties: {
42 | status: {
43 | type: "string",
44 | description:
45 | "Optional status to filter tickets (e.g. 'active', 'completed')",
46 | enum: ["active", "completed", "canceled"],
47 | },
48 | limit: {
49 | type: "number",
50 | description:
51 | "Maximum number of tickets to return (default: 10)",
52 | minimum: 1,
53 | maximum: 50,
54 | },
55 | },
56 | },
57 | },
58 | ],
59 | }));
60 |
61 | // Handle tool execution
62 | this.server.setRequestHandler(CallToolRequestSchema, async (request) => {
63 | if (request.params.name !== "get-linear-tickets") {
64 | throw new McpError(
65 | ErrorCode.MethodNotFound,
66 | `Unknown tool: ${request.params.name}`,
67 | );
68 | }
69 |
70 | const { handleRequest } = await import(
71 | "./requests/getTicketsRequestHandler.js"
72 | );
73 | return handleRequest(
74 | request.params.arguments as {
75 | apiKey: string;
76 | status?: "active" | "completed" | "canceled";
77 | limit?: number;
78 | },
79 | );
80 | });
81 | }
82 |
83 | async run(): Promise<void> {
84 | //dotenv.config();
85 | const apiKey = process.env.LINEAR_API_KEY;
86 | if (!apiKey) {
87 | console.error("LINEAR_API_KEY environment variable is required");
88 | process.exit(1);
89 | }
90 | const transport = new StdioServerTransport();
91 | await this.server.connect(transport);
92 | console.error("Linear MCP Server running on stdio");
93 | }
94 | }
95 |
96 | // Start the server
97 | const server = new LinearMcpServer();
98 | server.run().catch((error: Error) => {
99 | console.error("Fatal error:", error);
100 | process.exit(1);
101 | });
102 |
```
--------------------------------------------------------------------------------
/src/server/requests/getTicketsRequestHandler.test.ts:
--------------------------------------------------------------------------------
```typescript
1 | import { describe, it, expect, vi, beforeEach, Mock } from "vitest";
2 | import {
3 | LinearClient,
4 | User,
5 | IssueConnection,
6 | Organization,
7 | Team,
8 | } from "@linear/sdk";
9 | import type { LinearFetch } from "@linear/sdk";
10 | import { McpError, ErrorCode } from "@modelcontextprotocol/sdk/types.js";
11 | import { handleRequest } from "./getTicketsRequestHandler";
12 |
13 | // Mock Linear SDK
14 | vi.mock("@linear/sdk", () => ({
15 | LinearClient: vi.fn().mockImplementation(() => ({
16 | viewer: vi.fn(),
17 | })),
18 | }));
19 |
20 | // Get the mock constructor
21 | // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
22 | const MockLinearClient = LinearClient as unknown as Mock;
23 |
24 | describe("getTicketsRequestHandler", () => {
25 | beforeEach(() => {
26 | vi.clearAllMocks();
27 | });
28 |
29 | it("should throw an error if no API key is provided", async () => {
30 | // @ts-expect-error - Testing invalid input
31 | // eslint-disable-next-line @typescript-eslint/no-unsafe-call
32 | await expect(handleRequest({})).rejects.toThrow(
33 | new McpError(ErrorCode.InvalidParams, "API key is required"),
34 | );
35 | });
36 |
37 | it("should return appropriate message when no issues are found", async () => {
38 | // Mock Linear client to return empty issues list
39 | const mockIssueConnection: Partial<IssueConnection> = {
40 | nodes: [],
41 | };
42 |
43 | const mockAssignedIssues = vi.fn().mockResolvedValue(mockIssueConnection);
44 | const now = new Date();
45 |
46 | // Create a mock User with required properties
47 | const mockUser = {
48 | id: "test-user",
49 | name: "Test User",
50 | email: "[email protected]",
51 | active: true,
52 | admin: false,
53 | assignedIssues: mockAssignedIssues,
54 | createdAt: now,
55 | updatedAt: now,
56 | displayName: "Test User",
57 | avatarUrl: "test-url",
58 | avatarBackgroundColor: "#000000",
59 | createdIssueCount: 0,
60 | disableReason: undefined,
61 | guest: false,
62 | isMe: true,
63 | lastSeen: now,
64 | organization: Promise.resolve({
65 | id: "test-org",
66 | name: "Test Org",
67 | }) as LinearFetch<Organization>,
68 | statusEmoji: undefined,
69 | statusLabel: undefined,
70 | statusUntilAt: undefined,
71 | teamIds: ["test-team"],
72 | teams: (() => Promise.resolve({ nodes: [] as Team[] })) as User["teams"],
73 | timezone: "UTC",
74 | url: "test-url",
75 | } as Partial<User>;
76 |
77 | const mockViewer = Promise.resolve(mockUser) as LinearFetch<User>;
78 | const mockClient = {
79 | viewer: mockViewer,
80 | options: {},
81 | } as LinearClient;
82 |
83 | MockLinearClient.mockImplementation(() => mockClient);
84 |
85 | // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-call
86 | const result = await handleRequest({ apiKey: "test-key" });
87 |
88 | expect(result).toEqual({
89 | content: [
90 | {
91 | type: "text",
92 | text: "No tickets found matching the criteria.",
93 | },
94 | ],
95 | });
96 | });
97 |
98 | it("should handle unexpected errors properly", async () => {
99 | // Mock Linear client to throw an error
100 | const mockError = new Error("Unexpected API error");
101 | const mockViewer = Promise.reject(mockError) as LinearFetch<User>;
102 | const mockClient = {
103 | viewer: mockViewer,
104 | options: {},
105 | } as LinearClient;
106 |
107 | MockLinearClient.mockImplementation(() => mockClient);
108 |
109 | // eslint-disable-next-line @typescript-eslint/no-unsafe-call
110 | await expect(handleRequest({ apiKey: "test-key" })).rejects.toThrow(
111 | new McpError(
112 | ErrorCode.InternalError,
113 | "Failed to fetch Linear tickets: Unexpected API error",
114 | ),
115 | );
116 | });
117 | });
118 |
```
--------------------------------------------------------------------------------
/prompts/STEP_1_INITIAL_ANALYSIS.md:
--------------------------------------------------------------------------------
```markdown
1 | I'll provide guidance on creating an MCP Server for Linear integration. Based on the requirements, here's a high-level design approach:
2 |
3 | Project Setup:
4 | // Basic MCP Server structure
5 | import { Server } from "@modelcontextprotocol/sdk/server/index.js";
6 | import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
7 | import { LinearClient } from "@linear/sdk";
8 |
9 | // Server configuration
10 | const server = new Server(
11 | {
12 | name: "linear-mcp-server",
13 | version: "1.0.0",
14 | },
15 | {
16 | capabilities: {
17 | tools: {},
18 | },
19 | }
20 | );
21 | Tool Definitions: The server should expose these tools to handle the requested operations:
22 | // Tool definitions
23 | const tools = [
24 | {
25 | name: "get-assigned-tickets",
26 | description: "Get all Linear tickets assigned to the authenticated user",
27 | inputSchema: {
28 | type: "object",
29 | properties: {} // No input needed as it uses authenticated user
30 | }
31 | },
32 | {
33 | name: "get-tickets-by-status",
34 | description: "Get Linear tickets by status for authenticated user",
35 | inputSchema: {
36 | type: "object",
37 | properties: {
38 | status: {
39 | type: "string",
40 | description: "Status to filter tickets by"
41 | }
42 | },
43 | required: ["status"]
44 | }
45 | },
46 | {
47 | name: "search-tickets",
48 | description: "Search Linear tickets by title",
49 | inputSchema: {
50 | type: "object",
51 | properties: {
52 | query: {
53 | type: "string",
54 | description: "Search query for ticket titles"
55 | }
56 | },
57 | required: ["query"]
58 | }
59 | },
60 | {
61 | name: "get-suggested-branch",
62 | description: "Get suggested GitHub branch name for a ticket",
63 | inputSchema: {
64 | type: "object",
65 | properties: {
66 | ticketId: {
67 | type: "string",
68 | description: "ID of the Linear ticket"
69 | }
70 | },
71 | required: ["ticketId"]
72 | }
73 | },
74 | {
75 | name: "get-ticket-details",
76 | description: "Get full ticket details including comments",
77 | inputSchema: {
78 | type: "object",
79 | properties: {
80 | ticketId: {
81 | type: "string",
82 | description: "ID of the Linear ticket"
83 | }
84 | },
85 | required: ["ticketId"]
86 | }
87 | },
88 | {
89 | name: "update-ticket-description",
90 | description: "Update Linear ticket description",
91 | inputSchema: {
92 | type: "object",
93 | properties: {
94 | ticketId: {
95 | type: "string",
96 | description: "ID of the Linear ticket"
97 | },
98 | description: {
99 | type: "string",
100 | description: "New description"
101 | }
102 | },
103 | required: ["ticketId", "description"]
104 | }
105 | },
106 | {
107 | name: "update-ticket-status",
108 | description: "Update Linear ticket status",
109 | inputSchema: {
110 | type: "object",
111 | properties: {
112 | ticketId: {
113 | type: "string",
114 | description: "ID of the Linear ticket"
115 | },
116 | statusId: {
117 | type: "string",
118 | description: "ID of the new status"
119 | }
120 | },
121 | required: ["ticketId", "statusId"]
122 | }
123 | },
124 | {
125 | name: "add-ticket-comment",
126 | description: "Add comment to Linear ticket with optional user mentions",
127 | inputSchema: {
128 | type: "object",
129 | properties: {
130 | ticketId: {
131 | type: "string",
132 | description: "ID of the Linear ticket"
133 | },
134 | comment: {
135 | type: "string",
136 | description: "Comment text"
137 | },
138 | mentionUserIds: {
139 | type: "array",
140 | items: {
141 | type: "string"
142 | },
143 | description: "Optional array of user IDs to mention"
144 | }
145 | },
146 | required: ["ticketId", "comment"]
147 | }
148 | },
149 | {
150 | name: "create-ticket",
151 | description: "Create new Linear ticket",
152 | inputSchema: {
153 | type: "object",
154 | properties: {
155 | teamId: {
156 | type: "string",
157 | description: "ID of the team"
158 | },
159 | title: {
160 | type: "string",
161 | description: "Ticket title"
162 | },
163 | description: {
164 | type: "string",
165 | description: "Ticket description"
166 | }
167 | },
168 | required: ["teamId", "title"]
169 | }
170 | },
171 | {
172 | name: "get-subtasks",
173 | description: "Get subtasks for a Linear ticket",
174 | inputSchema: {
175 | type: "object",
176 | properties: {
177 | ticketId: {
178 | type: "string",
179 | description: "ID of the parent ticket"
180 | }
181 | },
182 | required: ["ticketId"]
183 | }
184 | },
185 | {
186 | name: "create-subtask",
187 | description: "Create subtask for a Linear ticket",
188 | inputSchema: {
189 | type: "object",
190 | properties: {
191 | parentTicketId: {
192 | type: "string",
193 | description: "ID of the parent ticket"
194 | },
195 | title: {
196 | type: "string",
197 | description: "Subtask title"
198 | },
199 | description: {
200 | type: "string",
201 | description: "Subtask description"
202 | }
203 | },
204 | required: ["parentTicketId", "title"]
205 | }
206 | }
207 | ];
208 | Implementation Considerations:
209 | Authentication:
210 | // Linear client initialization with API key
211 | const linearClient = new LinearClient({
212 | apiKey: process.env.LINEAR_API_KEY
213 | });
214 | Error Handling:
215 | // Example error handling wrapper
216 | const handleLinearOperation = async (operation: () => Promise<any>) => {
217 | try {
218 | return await operation();
219 | } catch (error) {
220 | throw new McpError(
221 | ErrorCode.InternalError,
222 | `Linear API error: ${error.message}`
223 | );
224 | }
225 | };
226 | Configuration: The MCP server would need to be configured in the Claude desktop config:
227 | {
228 | "mcpServers": {
229 | "linear": {
230 | "command": "node",
231 | "args": ["/path/to/linear-mcp-server/build/index.js"],
232 | "env": {
233 | "LINEAR_API_KEY": "your-linear-api-key"
234 | }
235 | }
236 | }
237 | }
238 | Security Considerations:
239 | Store Linear API key securely
240 | Validate all input parameters
241 | Implement rate limiting
242 | Handle authentication errors gracefully
243 | Sanitize output data
244 | Best Practices:
245 | Use TypeScript for type safety
246 | Implement comprehensive error handling
247 | Add logging for debugging
248 | Write unit tests
249 | Document all tools and their usage
250 | Follow Linear API best practices
251 | Cache responses where appropriate
252 | Implement retry logic for API calls
253 | The implementation would require:
254 |
255 | Setting up a new Node.js project
256 | Installing required dependencies (@modelcontextprotocol/sdk, @linear/sdk)
257 | Implementing the server and tools
258 | Adding proper error handling and validation
259 | Testing the integration
260 | Deploying and configuring with Claude
261 | This design provides a foundation for building a Linear MCP server that can handle all the requested operations while following MCP best practices and security considerations.
262 |
263 | Task Completed
264 | I've provided a high-level design for creating an MCP Server that integrates with Linear. The design includes:
265 |
266 | Basic server structure and configuration
267 | Comprehensive tool definitions for all requested Linear operations
268 | Authentication and error handling patterns
269 | Configuration requirements
270 | Security considerations and best practices
271 | This design would allow for all requested operations:
272 |
273 | Finding and searching Linear tickets
274 | Getting ticket details and branch names
275 | Updating tickets and their statuses
276 | Managing comments and mentions
277 | Creating tickets and subtasks
278 | The implementation would use the Linear SDK for API interactions and the MCP SDK for server functionality, providing a secure and efficient way to interact with Linear through Claude.
279 |
```
--------------------------------------------------------------------------------
/prompts/MCP_REFERENCE_DOCS.md:
--------------------------------------------------------------------------------
```markdown
1 | The following is information on building MCP Server Applications
2 | The following is from the documents from the MCP Site
3 |
4 | ###
5 |
6 | Get Started
7 | Introduction
8 | Get started with the Model Context Protocol (MCP)
9 |
10 | MCP is an open protocol that standardizes how applications provide context to LLMs. Think of MCP like a USB-C port for AI applications. Just as USB-C provides a standardized way to connect your devices to various peripherals and accessories, MCP provides a standardized way to connect AI models to different data sources and tools.
11 |
12 |
13 | Why MCP?
14 | MCP helps you build agents and complex workflows on top of LLMs. LLMs frequently need to integrate with data and tools, and MCP provides:
15 |
16 | A growing list of pre-built integrations that your LLM can directly plug into
17 | The flexibility to switch between LLM providers and vendors
18 | Best practices for securing your data within your infrastructure
19 |
20 | General architecture
21 | At its core, MCP follows a client-server architecture where a host application can connect to multiple servers:
22 |
23 | Internet
24 |
25 | Your Computer
26 |
27 | MCP Protocol
28 |
29 | MCP Protocol
30 |
31 | MCP Protocol
32 |
33 | Web APIs
34 |
35 | Host with MCP Client
36 | (Claude, IDEs, Tools)
37 |
38 | MCP Server A
39 |
40 | MCP Server B
41 |
42 | MCP Server C
43 |
44 | Local
45 | Data Source A
46 |
47 | Local
48 | Data Source B
49 |
50 | Remote
51 | Service C
52 |
53 | MCP Hosts: Programs like Claude Desktop, IDEs, or AI tools that want to access data through MCP
54 | MCP Clients: Protocol clients that maintain 1:1 connections with servers
55 | MCP Servers: Lightweight programs that each expose specific capabilities through the standardized Model Context Protocol
56 | Local Data Sources: Your computer’s files, databases, and services that MCP servers can securely access
57 | Remote Services: External systems available over the internet (e.g., through APIs) that MCP servers can connect to
58 |
59 |
60 | ###
61 |
62 | Here is information on MCP Core Architecture
63 |
64 | ###
65 |
66 | Core architecture
67 | Understand how MCP connects clients, servers, and LLMs
68 |
69 | The Model Context Protocol (MCP) is built on a flexible, extensible architecture that enables seamless communication between LLM applications and integrations. This document covers the core architectural components and concepts.
70 |
71 |
72 | Overview
73 | MCP follows a client-server architecture where:
74 |
75 | Hosts are LLM applications (like Claude Desktop or IDEs) that initiate connections
76 | Clients maintain 1:1 connections with servers, inside the host application
77 | Servers provide context, tools, and prompts to clients
78 | Server Process
79 |
80 | Server Process
81 |
82 | Host (e.g., Claude Desktop)
83 |
84 | Transport Layer
85 |
86 | Transport Layer
87 |
88 | MCP Client
89 |
90 | MCP Client
91 |
92 | MCP Server
93 |
94 | MCP Server
95 |
96 |
97 | Core components
98 |
99 | Protocol layer
100 | The protocol layer handles message framing, request/response linking, and high-level communication patterns.
101 |
102 | TypeScript
103 | Python
104 |
105 | class Protocol<Request, Notification, Result> {
106 | // Handle incoming requests
107 | setRequestHandler<T>(schema: T, handler: (request: T, extra: RequestHandlerExtra) => Promise<Result>): void
108 |
109 | // Handle incoming notifications
110 | setNotificationHandler<T>(schema: T, handler: (notification: T) => Promise<void>): void
111 |
112 | // Send requests and await responses
113 | request<T>(request: Request, schema: T, options?: RequestOptions): Promise<T>
114 |
115 | // Send one-way notifications
116 | notification(notification: Notification): Promise<void>
117 |
118 | }
119 | Key classes include:
120 |
121 | Protocol
122 | Client
123 | Server
124 |
125 | Transport layer
126 | The transport layer handles the actual communication between clients and servers. MCP supports multiple transport mechanisms:
127 |
128 | Stdio transport
129 |
130 | Uses standard input/output for communication
131 | Ideal for local processes
132 | HTTP with SSE transport
133 |
134 | Uses Server-Sent Events for server-to-client messages
135 | HTTP POST for client-to-server messages
136 | All transports use JSON-RPC 2.0 to exchange messages. See the specification for detailed information about the Model Context Protocol message format.
137 |
138 |
139 | Message types
140 | MCP has these main types of messages:
141 |
142 | Requests expect a response from the other side:
143 |
144 | interface Request {
145 | method: string;
146 | params?: { ... };
147 | }
148 | Results are successful responses to requests:
149 |
150 | interface Result {
151 | [key: string]: unknown;
152 | }
153 | Errors indicate that a request failed:
154 |
155 | interface Error {
156 | code: number;
157 | message: string;
158 | data?: unknown;
159 | }
160 | Notifications are one-way messages that don’t expect a response:
161 |
162 | interface Notification {
163 | method: string;
164 | params?: { ... };
165 | }
166 |
167 | Connection lifecycle
168 |
169 |
170 | 1. Initialization
171 | Server
172 | Client
173 | Server
174 | Client
175 | Connection ready for use
176 | initialize request
177 | initialize response
178 | initialized notification
179 | Client sends initialize request with protocol version and capabilities
180 | Server responds with its protocol version and capabilities
181 | Client sends initialized notification as acknowledgment
182 | Normal message exchange begins
183 |
184 | 2. Message exchange
185 | After initialization, the following patterns are supported:
186 |
187 | Request-Response: Client or server sends requests, the other responds
188 | Notifications: Either party sends one-way messages
189 | 3. Termination
190 | Either party can terminate the connection:
191 |
192 | Clean shutdown via close()
193 | Transport disconnection
194 | Error conditions
195 |
196 | Error handling
197 | MCP defines these standard error codes:
198 |
199 | enum ErrorCode {
200 | // Standard JSON-RPC error codes
201 | ParseError = -32700,
202 | InvalidRequest = -32600,
203 | MethodNotFound = -32601,
204 | InvalidParams = -32602,
205 | InternalError = -32603
206 | }
207 | SDKs and applications can define their own error codes above -32000.
208 |
209 | Errors are propagated through:
210 |
211 | Error responses to requests
212 | Error events on transports
213 | Protocol-level error handlers
214 |
215 | Implementation example
216 | Here’s a basic example of implementing an MCP server:
217 |
218 | TypeScript
219 | Python
220 |
221 | import { Server } from "@modelcontextprotocol/sdk/server/index.js";
222 | import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
223 |
224 | const server = new Server({
225 | name: "example-server",
226 | version: "1.0.0"
227 | }, {
228 | capabilities: {
229 | resources: {}
230 | }
231 | });
232 |
233 | // Handle requests
234 | server.setRequestHandler(ListResourcesRequestSchema, async () => {
235 | return {
236 | resources: [
237 | {
238 | uri: "example://resource",
239 | name: "Example Resource"
240 | }
241 | ]
242 | };
243 | });
244 |
245 | // Connect transport
246 | const transport = new StdioServerTransport();
247 | await server.connect(transport);
248 |
249 | Best practices
250 |
251 | Transport selection
252 | Local communication
253 |
254 | Use stdio transport for local processes
255 | Efficient for same-machine communication
256 | Simple process management
257 | Remote communication
258 |
259 | Use SSE for scenarios requiring HTTP compatibility
260 | Consider security implications including authentication and authorization
261 |
262 | Message handling
263 | Request processing
264 |
265 | Validate inputs thoroughly
266 | Use type-safe schemas
267 | Handle errors gracefully
268 | Implement timeouts
269 | Progress reporting
270 |
271 | Use progress tokens for long operations
272 | Report progress incrementally
273 | Include total progress when known
274 | Error management
275 |
276 | Use appropriate error codes
277 | Include helpful error messages
278 | Clean up resources on errors
279 |
280 | Security considerations
281 | Transport security
282 |
283 | Use TLS for remote connections
284 | Validate connection origins
285 | Implement authentication when needed
286 | Message validation
287 |
288 | Validate all incoming messages
289 | Sanitize inputs
290 | Check message size limits
291 | Verify JSON-RPC format
292 | Resource protection
293 |
294 | Implement access controls
295 | Validate resource paths
296 | Monitor resource usage
297 | Rate limit requests
298 | Error handling
299 |
300 | Don’t leak sensitive information
301 | Log security-relevant errors
302 | Implement proper cleanup
303 | Handle DoS scenarios
304 |
305 | Debugging and monitoring
306 | Logging
307 |
308 | Log protocol events
309 | Track message flow
310 | Monitor performance
311 | Record errors
312 | Diagnostics
313 |
314 | Implement health checks
315 | Monitor connection state
316 | Track resource usage
317 | Profile performance
318 | Testing
319 |
320 | Test different transports
321 | Verify error handling
322 | Check edge cases
323 | Load test servers
324 |
325 | ###
326 |
327 | Here is documentation onf MCP Resources
328 |
329 | ###
330 |
331 | Resources
332 | Expose data and content from your servers to LLMs
333 |
334 | Resources are a core primitive in the Model Context Protocol (MCP) that allow servers to expose data and content that can be read by clients and used as context for LLM interactions.
335 |
336 | Resources are designed to be application-controlled, meaning that the client application can decide how and when they should be used. Different MCP clients may handle resources differently. For example:
337 |
338 | Claude Desktop currently requires users to explicitly select resources before they can be used
339 | Other clients might automatically select resources based on heuristics
340 | Some implementations may even allow the AI model itself to determine which resources to use
341 | Server authors should be prepared to handle any of these interaction patterns when implementing resource support. In order to expose data to models automatically, server authors should use a model-controlled primitive such as Tools.
342 |
343 |
344 | Overview
345 | Resources represent any kind of data that an MCP server wants to make available to clients. This can include:
346 |
347 | File contents
348 | Database records
349 | API responses
350 | Live system data
351 | Screenshots and images
352 | Log files
353 | And more
354 | Each resource is identified by a unique URI and can contain either text or binary data.
355 |
356 |
357 | Resource URIs
358 | Resources are identified using URIs that follow this format:
359 |
360 | [protocol]://[host]/[path]
361 | For example:
362 |
363 | file:///home/user/documents/report.pdf
364 | postgres://database/customers/schema
365 | screen://localhost/display1
366 | The protocol and path structure is defined by the MCP server implementation. Servers can define their own custom URI schemes.
367 |
368 |
369 | Resource types
370 | Resources can contain two types of content:
371 |
372 |
373 | Text resources
374 | Text resources contain UTF-8 encoded text data. These are suitable for:
375 |
376 | Source code
377 | Configuration files
378 | Log files
379 | JSON/XML data
380 | Plain text
381 |
382 | Binary resources
383 | Binary resources contain raw binary data encoded in base64. These are suitable for:
384 |
385 | Images
386 | PDFs
387 | Audio files
388 | Video files
389 | Other non-text formats
390 |
391 | Resource discovery
392 | Clients can discover available resources through two main methods:
393 |
394 |
395 | Direct resources
396 | Servers expose a list of concrete resources via the resources/list endpoint. Each resource includes:
397 |
398 | {
399 | uri: string; // Unique identifier for the resource
400 | name: string; // Human-readable name
401 | description?: string; // Optional description
402 | mimeType?: string; // Optional MIME type
403 | }
404 |
405 | Resource templates
406 | For dynamic resources, servers can expose URI templates that clients can use to construct valid resource URIs:
407 |
408 | {
409 | uriTemplate: string; // URI template following RFC 6570
410 | name: string; // Human-readable name for this type
411 | description?: string; // Optional description
412 | mimeType?: string; // Optional MIME type for all matching resources
413 | }
414 |
415 | Reading resources
416 | To read a resource, clients make a resources/read request with the resource URI.
417 |
418 | The server responds with a list of resource contents:
419 |
420 | {
421 | contents: [
422 | {
423 | uri: string; // The URI of the resource
424 | mimeType?: string; // Optional MIME type
425 |
426 | // One of:
427 | text?: string; // For text resources
428 | blob?: string; // For binary resources (base64 encoded)
429 | }
430 |
431 | ]
432 | }
433 | Servers may return multiple resources in response to one resources/read request. This could be used, for example, to return a list of files inside a directory when the directory is read.
434 |
435 |
436 | Resource updates
437 | MCP supports real-time updates for resources through two mechanisms:
438 |
439 |
440 | List changes
441 | Servers can notify clients when their list of available resources changes via the notifications/resources/list_changed notification.
442 |
443 |
444 | Content changes
445 | Clients can subscribe to updates for specific resources:
446 |
447 | Client sends resources/subscribe with resource URI
448 | Server sends notifications/resources/updated when the resource changes
449 | Client can fetch latest content with resources/read
450 | Client can unsubscribe with resources/unsubscribe
451 |
452 | Example implementation
453 | Here’s a simple example of implementing resource support in an MCP server:
454 |
455 | TypeScript
456 | Python
457 |
458 | const server = new Server({
459 | name: "example-server",
460 | version: "1.0.0"
461 | }, {
462 | capabilities: {
463 | resources: {}
464 | }
465 | });
466 |
467 | // List available resources
468 | server.setRequestHandler(ListResourcesRequestSchema, async () => {
469 | return {
470 | resources: [
471 | {
472 | uri: "file:///logs/app.log",
473 | name: "Application Logs",
474 | mimeType: "text/plain"
475 | }
476 | ]
477 | };
478 | });
479 |
480 | // Read resource contents
481 | server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
482 | const uri = request.params.uri;
483 |
484 | if (uri === "file:///logs/app.log") {
485 | const logContents = await readLogFile();
486 | return {
487 | contents: [
488 | {
489 | uri,
490 | mimeType: "text/plain",
491 | text: logContents
492 | }
493 | ]
494 | };
495 | }
496 |
497 | throw new Error("Resource not found");
498 | });
499 |
500 | Best practices
501 | When implementing resource support:
502 |
503 | Use clear, descriptive resource names and URIs
504 | Include helpful descriptions to guide LLM understanding
505 | Set appropriate MIME types when known
506 | Implement resource templates for dynamic content
507 | Use subscriptions for frequently changing resources
508 | Handle errors gracefully with clear error messages
509 | Consider pagination for large resource lists
510 | Cache resource contents when appropriate
511 | Validate URIs before processing
512 | Document your custom URI schemes
513 |
514 | Security considerations
515 | When exposing resources:
516 |
517 | Validate all resource URIs
518 | Implement appropriate access controls
519 | Sanitize file paths to prevent directory traversal
520 | Be cautious with binary data handling
521 | Consider rate limiting for resource reads
522 | Audit resource access
523 | Encrypt sensitive data in transit
524 | Validate MIME types
525 | Implement timeouts for long-running reads
526 | Handle resource cleanup appropriately
527 | Was this page helpful?
528 |
529 | ###
530 |
531 | Here is information on MCP Tools
532 |
533 | ###
534 |
535 | Concepts
536 | Tools
537 | Enable LLMs to perform actions through your server
538 |
539 | Tools are a powerful primitive in the Model Context Protocol (MCP) that enable servers to expose executable functionality to clients. Through tools, LLMs can interact with external systems, perform computations, and take actions in the real world.
540 |
541 | Tools are designed to be model-controlled, meaning that tools are exposed from servers to clients with the intention of the AI model being able to automatically invoke them (with a human in the loop to grant approval).
542 |
543 |
544 | Overview
545 | Tools in MCP allow servers to expose executable functions that can be invoked by clients and used by LLMs to perform actions. Key aspects of tools include:
546 |
547 | Discovery: Clients can list available tools through the tools/list endpoint
548 | Invocation: Tools are called using the tools/call endpoint, where servers perform the requested operation and return results
549 | Flexibility: Tools can range from simple calculations to complex API interactions
550 | Like resources, tools are identified by unique names and can include descriptions to guide their usage. However, unlike resources, tools represent dynamic operations that can modify state or interact with external systems.
551 |
552 |
553 | Tool definition structure
554 | Each tool is defined with the following structure:
555 |
556 | {
557 | name: string; // Unique identifier for the tool
558 | description?: string; // Human-readable description
559 | inputSchema: { // JSON Schema for the tool's parameters
560 | type: "object",
561 | properties: { ... } // Tool-specific parameters
562 | }
563 | }
564 |
565 | Implementing tools
566 | Here’s an example of implementing a basic tool in an MCP server:
567 |
568 | TypeScript
569 | Python
570 |
571 | const server = new Server({
572 | name: "example-server",
573 | version: "1.0.0"
574 | }, {
575 | capabilities: {
576 | tools: {}
577 | }
578 | });
579 |
580 | // Define available tools
581 | server.setRequestHandler(ListToolsRequestSchema, async () => {
582 | return {
583 | tools: [{
584 | name: "calculate_sum",
585 | description: "Add two numbers together",
586 | inputSchema: {
587 | type: "object",
588 | properties: {
589 | a: { type: "number" },
590 | b: { type: "number" }
591 | },
592 | required: ["a", "b"]
593 | }
594 | }]
595 | };
596 | });
597 |
598 | // Handle tool execution
599 | server.setRequestHandler(CallToolRequestSchema, async (request) => {
600 | if (request.params.name === "calculate_sum") {
601 | const { a, b } = request.params.arguments;
602 | return {
603 | content: [
604 | {
605 | type: "text",
606 | text: String(a + b)
607 | }
608 | ]
609 | };
610 | }
611 | throw new Error("Tool not found");
612 | });
613 |
614 | Example tool patterns
615 | Here are some examples of types of tools that a server could provide:
616 |
617 |
618 | System operations
619 | Tools that interact with the local system:
620 |
621 | {
622 | name: "execute_command",
623 | description: "Run a shell command",
624 | inputSchema: {
625 | type: "object",
626 | properties: {
627 | command: { type: "string" },
628 | args: { type: "array", items: { type: "string" } }
629 | }
630 | }
631 | }
632 |
633 | API integrations
634 | Tools that wrap external APIs:
635 |
636 | {
637 | name: "github_create_issue",
638 | description: "Create a GitHub issue",
639 | inputSchema: {
640 | type: "object",
641 | properties: {
642 | title: { type: "string" },
643 | body: { type: "string" },
644 | labels: { type: "array", items: { type: "string" } }
645 | }
646 | }
647 | }
648 |
649 | Data processing
650 | Tools that transform or analyze data:
651 |
652 | {
653 | name: "analyze_csv",
654 | description: "Analyze a CSV file",
655 | inputSchema: {
656 | type: "object",
657 | properties: {
658 | filepath: { type: "string" },
659 | operations: {
660 | type: "array",
661 | items: {
662 | enum: ["sum", "average", "count"]
663 | }
664 | }
665 | }
666 | }
667 | }
668 |
669 | Best practices
670 | When implementing tools:
671 |
672 | Provide clear, descriptive names and descriptions
673 | Use detailed JSON Schema definitions for parameters
674 | Include examples in tool descriptions to demonstrate how the model should use them
675 | Implement proper error handling and validation
676 | Use progress reporting for long operations
677 | Keep tool operations focused and atomic
678 | Document expected return value structures
679 | Implement proper timeouts
680 | Consider rate limiting for resource-intensive operations
681 | Log tool usage for debugging and monitoring
682 |
683 | Security considerations
684 | When exposing tools:
685 |
686 |
687 | Input validation
688 | Validate all parameters against the schema
689 | Sanitize file paths and system commands
690 | Validate URLs and external identifiers
691 | Check parameter sizes and ranges
692 | Prevent command injection
693 |
694 | Access control
695 | Implement authentication where needed
696 | Use appropriate authorization checks
697 | Audit tool usage
698 | Rate limit requests
699 | Monitor for abuse
700 |
701 | Error handling
702 | Don’t expose internal errors to clients
703 | Log security-relevant errors
704 | Handle timeouts appropriately
705 | Clean up resources after errors
706 | Validate return values
707 |
708 | Tool discovery and updates
709 | MCP supports dynamic tool discovery:
710 |
711 | Clients can list available tools at any time
712 | Servers can notify clients when tools change using notifications/tools/list_changed
713 | Tools can be added or removed during runtime
714 | Tool definitions can be updated (though this should be done carefully)
715 |
716 | Error handling
717 | Tool errors should be reported within the result object, not as MCP protocol-level errors. This allows the LLM to see and potentially handle the error. When a tool encounters an error:
718 |
719 | Set isError to true in the result
720 | Include error details in the content array
721 | Here’s an example of proper error handling for tools:
722 |
723 | TypeScript
724 | Python
725 |
726 | try {
727 | // Tool operation
728 | const result = performOperation();
729 | return {
730 | content: [
731 | {
732 | type: "text",
733 | text: `Operation successful: ${result}`
734 | }
735 | ]
736 | };
737 | } catch (error) {
738 | return {
739 | isError: true,
740 | content: [
741 | {
742 | type: "text",
743 | text: `Error: ${error.message}`
744 | }
745 | ]
746 | };
747 | }
748 | This approach allows the LLM to see that an error occurred and potentially take corrective action or request human intervention.
749 |
750 |
751 | Testing tools
752 | A comprehensive testing strategy for MCP tools should cover:
753 |
754 | Functional testing: Verify tools execute correctly with valid inputs and handle invalid inputs appropriately
755 | Integration testing: Test tool interaction with external systems using both real and mocked dependencies
756 | Security testing: Validate authentication, authorization, input sanitization, and rate limiting
757 | Performance testing: Check behavior under load, timeout handling, and resource cleanup
758 | Error handling: Ensure tools properly report errors through the MCP protocol and clean up resources
759 |
760 | ###
761 |
762 | Here is information on MCP Prompts
763 |
764 | ###
765 |
766 | Concepts
767 | Prompts
768 | Create reusable prompt templates and workflows
769 |
770 | Prompts enable servers to define reusable prompt templates and workflows that clients can easily surface to users and LLMs. They provide a powerful way to standardize and share common LLM interactions.
771 |
772 | Prompts are designed to be user-controlled, meaning they are exposed from servers to clients with the intention of the user being able to explicitly select them for use.
773 |
774 |
775 | Overview
776 | Prompts in MCP are predefined templates that can:
777 |
778 | Accept dynamic arguments
779 | Include context from resources
780 | Chain multiple interactions
781 | Guide specific workflows
782 | Surface as UI elements (like slash commands)
783 |
784 | Prompt structure
785 | Each prompt is defined with:
786 |
787 | {
788 | name: string; // Unique identifier for the prompt
789 | description?: string; // Human-readable description
790 | arguments?: [ // Optional list of arguments
791 | {
792 | name: string; // Argument identifier
793 | description?: string; // Argument description
794 | required?: boolean; // Whether argument is required
795 | }
796 | ]
797 | }
798 |
799 | Discovering prompts
800 | Clients can discover available prompts through the prompts/list endpoint:
801 |
802 | // Request
803 | {
804 | method: "prompts/list"
805 | }
806 |
807 | // Response
808 | {
809 | prompts: [
810 | {
811 | name: "analyze-code",
812 | description: "Analyze code for potential improvements",
813 | arguments: [
814 | {
815 | name: "language",
816 | description: "Programming language",
817 | required: true
818 | }
819 | ]
820 | }
821 | ]
822 | }
823 |
824 | Using prompts
825 | To use a prompt, clients make a prompts/get request:
826 |
827 | // Request
828 | {
829 | method: "prompts/get",
830 | params: {
831 | name: "analyze-code",
832 | arguments: {
833 | language: "python"
834 | }
835 | }
836 | }
837 |
838 | // Response
839 | {
840 | description: "Analyze Python code for potential improvements",
841 | messages: [
842 | {
843 | role: "user",
844 | content: {
845 | type: "text",
846 | text: "Please analyze the following Python code for potential improvements:\n\n`python\ndef calculate_sum(numbers):\n total = 0\n for num in numbers:\n total = total + num\n return total\n\nresult = calculate_sum([1, 2, 3, 4, 5])\nprint(result)\n`"
847 | }
848 | }
849 | ]
850 | }
851 |
852 | Dynamic prompts
853 | Prompts can be dynamic and include:
854 |
855 |
856 | Embedded resource context
857 |
858 | {
859 | "name": "analyze-project",
860 | "description": "Analyze project logs and code",
861 | "arguments": [
862 | {
863 | "name": "timeframe",
864 | "description": "Time period to analyze logs",
865 | "required": true
866 | },
867 | {
868 | "name": "fileUri",
869 | "description": "URI of code file to review",
870 | "required": true
871 | }
872 | ]
873 | }
874 | When handling the prompts/get request:
875 |
876 | {
877 | "messages": [
878 | {
879 | "role": "user",
880 | "content": {
881 | "type": "text",
882 | "text": "Analyze these system logs and the code file for any issues:"
883 | }
884 | },
885 | {
886 | "role": "user",
887 | "content": {
888 | "type": "resource",
889 | "resource": {
890 | "uri": "logs://recent?timeframe=1h",
891 | "text": "[2024-03-14 15:32:11] ERROR: Connection timeout in network.py:127\n[2024-03-14 15:32:15] WARN: Retrying connection (attempt 2/3)\n[2024-03-14 15:32:20] ERROR: Max retries exceeded",
892 | "mimeType": "text/plain"
893 | }
894 | }
895 | },
896 | {
897 | "role": "user",
898 | "content": {
899 | "type": "resource",
900 | "resource": {
901 | "uri": "file:///path/to/code.py",
902 | "text": "def connect_to_service(timeout=30):\n retries = 3\n for attempt in range(retries):\n try:\n return establish_connection(timeout)\n except TimeoutError:\n if attempt == retries - 1:\n raise\n time.sleep(5)\n\ndef establish_connection(timeout):\n # Connection implementation\n pass",
903 | "mimeType": "text/x-python"
904 | }
905 | }
906 | }
907 | ]
908 | }
909 |
910 | Multi-step workflows
911 |
912 | const debugWorkflow = {
913 | name: "debug-error",
914 | async getMessages(error: string) {
915 | return [
916 | {
917 | role: "user",
918 | content: {
919 | type: "text",
920 | text: `Here's an error I'm seeing: ${error}`
921 | }
922 | },
923 | {
924 | role: "assistant",
925 | content: {
926 | type: "text",
927 | text: "I'll help analyze this error. What have you tried so far?"
928 | }
929 | },
930 | {
931 | role: "user",
932 | content: {
933 | type: "text",
934 | text: "I've tried restarting the service, but the error persists."
935 | }
936 | }
937 | ];
938 | }
939 | };
940 |
941 | Example implementation
942 | Here’s a complete example of implementing prompts in an MCP server:
943 |
944 | TypeScript
945 | Python
946 |
947 | import { Server } from "@modelcontextprotocol/sdk/server";
948 | import {
949 | ListPromptsRequestSchema,
950 | GetPromptRequestSchema
951 | } from "@modelcontextprotocol/sdk/types";
952 |
953 | const PROMPTS = {
954 | "git-commit": {
955 | name: "git-commit",
956 | description: "Generate a Git commit message",
957 | arguments: [
958 | {
959 | name: "changes",
960 | description: "Git diff or description of changes",
961 | required: true
962 | }
963 | ]
964 | },
965 | "explain-code": {
966 | name: "explain-code",
967 | description: "Explain how code works",
968 | arguments: [
969 | {
970 | name: "code",
971 | description: "Code to explain",
972 | required: true
973 | },
974 | {
975 | name: "language",
976 | description: "Programming language",
977 | required: false
978 | }
979 | ]
980 | }
981 | };
982 |
983 | const server = new Server({
984 | name: "example-prompts-server",
985 | version: "1.0.0"
986 | }, {
987 | capabilities: {
988 | prompts: {}
989 | }
990 | });
991 |
992 | // List available prompts
993 | server.setRequestHandler(ListPromptsRequestSchema, async () => {
994 | return {
995 | prompts: Object.values(PROMPTS)
996 | };
997 | });
998 |
999 | // Get specific prompt
1000 | server.setRequestHandler(GetPromptRequestSchema, async (request) => {
1001 | const prompt = PROMPTS[request.params.name];
1002 | if (!prompt) {
1003 | throw new Error(`Prompt not found: ${request.params.name}`);
1004 | }
1005 |
1006 | if (request.params.name === "git-commit") {
1007 | return {
1008 | messages: [
1009 | {
1010 | role: "user",
1011 | content: {
1012 | type: "text",
1013 | text: `Generate a concise but descriptive commit message for these changes:\n\n${request.params.arguments?.changes}`
1014 | }
1015 | }
1016 | ]
1017 | };
1018 | }
1019 |
1020 | if (request.params.name === "explain-code") {
1021 | const language = request.params.arguments?.language || "Unknown";
1022 | return {
1023 | messages: [
1024 | {
1025 | role: "user",
1026 | content: {
1027 | type: "text",
1028 | text: `Explain how this ${language} code works:\n\n${request.params.arguments?.code}`
1029 | }
1030 | }
1031 | ]
1032 | };
1033 | }
1034 |
1035 | throw new Error("Prompt implementation not found");
1036 | });
1037 |
1038 | Best practices
1039 | When implementing prompts:
1040 |
1041 | Use clear, descriptive prompt names
1042 | Provide detailed descriptions for prompts and arguments
1043 | Validate all required arguments
1044 | Handle missing arguments gracefully
1045 | Consider versioning for prompt templates
1046 | Cache dynamic content when appropriate
1047 | Implement error handling
1048 | Document expected argument formats
1049 | Consider prompt composability
1050 | Test prompts with various inputs
1051 |
1052 | UI integration
1053 | Prompts can be surfaced in client UIs as:
1054 |
1055 | Slash commands
1056 | Quick actions
1057 | Context menu items
1058 | Command palette entries
1059 | Guided workflows
1060 | Interactive forms
1061 |
1062 | Updates and changes
1063 | Servers can notify clients about prompt changes:
1064 |
1065 | Server capability: prompts.listChanged
1066 | Notification: notifications/prompts/list_changed
1067 | Client re-fetches prompt list
1068 |
1069 | Security considerations
1070 | When implementing prompts:
1071 |
1072 | Validate all arguments
1073 | Sanitize user input
1074 | Consider rate limiting
1075 | Implement access controls
1076 | Audit prompt usage
1077 | Handle sensitive data appropriately
1078 | Validate generated content
1079 | Implement timeouts
1080 | Consider prompt injection risks
1081 | Document security requirements
1082 |
1083 | ###
1084 |
1085 | Here is information for MCP Transport
1086 |
1087 | ###
1088 |
1089 | Transports
1090 | Learn about MCP’s communication mechanisms
1091 |
1092 | Transports in the Model Context Protocol (MCP) provide the foundation for communication between clients and servers. A transport handles the underlying mechanics of how messages are sent and received.
1093 |
1094 |
1095 | Message Format
1096 | MCP uses JSON-RPC 2.0 as its wire format. The transport layer is responsible for converting MCP protocol messages into JSON-RPC format for transmission and converting received JSON-RPC messages back into MCP protocol messages.
1097 |
1098 | There are three types of JSON-RPC messages used:
1099 |
1100 |
1101 | Requests
1102 |
1103 | {
1104 | jsonrpc: "2.0",
1105 | id: number | string,
1106 | method: string,
1107 | params?: object
1108 | }
1109 |
1110 | Responses
1111 |
1112 | {
1113 | jsonrpc: "2.0",
1114 | id: number | string,
1115 | result?: object,
1116 | error?: {
1117 | code: number,
1118 | message: string,
1119 | data?: unknown
1120 | }
1121 | }
1122 |
1123 | Notifications
1124 |
1125 | {
1126 | jsonrpc: "2.0",
1127 | method: string,
1128 | params?: object
1129 | }
1130 |
1131 | Built-in Transport Types
1132 | MCP includes two standard transport implementations:
1133 |
1134 |
1135 | Standard Input/Output (stdio)
1136 | The stdio transport enables communication through standard input and output streams. This is particularly useful for local integrations and command-line tools.
1137 |
1138 | Use stdio when:
1139 |
1140 | Building command-line tools
1141 | Implementing local integrations
1142 | Needing simple process communication
1143 | Working with shell scripts
1144 | TypeScript (Server)
1145 | TypeScript (Client)
1146 | Python (Server)
1147 | Python (Client)
1148 |
1149 | const server = new Server({
1150 | name: "example-server",
1151 | version: "1.0.0"
1152 | }, {
1153 | capabilities: {}
1154 | });
1155 |
1156 | const transport = new StdioServerTransport();
1157 | await server.connect(transport);
1158 |
1159 | Server-Sent Events (SSE)
1160 | SSE transport enables server-to-client streaming with HTTP POST requests for client-to-server communication.
1161 |
1162 | Use SSE when:
1163 |
1164 | Only server-to-client streaming is needed
1165 | Working with restricted networks
1166 | Implementing simple updates
1167 | TypeScript (Server)
1168 | TypeScript (Client)
1169 | Python (Server)
1170 | Python (Client)
1171 |
1172 | const server = new Server({
1173 | name: "example-server",
1174 | version: "1.0.0"
1175 | }, {
1176 | capabilities: {}
1177 | });
1178 |
1179 | const transport = new SSEServerTransport("/message", response);
1180 | await server.connect(transport);
1181 |
1182 | Custom Transports
1183 | MCP makes it easy to implement custom transports for specific needs. Any transport implementation just needs to conform to the Transport interface:
1184 |
1185 | You can implement custom transports for:
1186 |
1187 | Custom network protocols
1188 | Specialized communication channels
1189 | Integration with existing systems
1190 | Performance optimization
1191 | TypeScript
1192 | Python
1193 |
1194 | interface Transport {
1195 | // Start processing messages
1196 | start(): Promise<void>;
1197 |
1198 | // Send a JSON-RPC message
1199 | send(message: JSONRPCMessage): Promise<void>;
1200 |
1201 | // Close the connection
1202 | close(): Promise<void>;
1203 |
1204 | // Callbacks
1205 | onclose?: () => void;
1206 | onerror?: (error: Error) => void;
1207 | onmessage?: (message: JSONRPCMessage) => void;
1208 | }
1209 |
1210 | Error Handling
1211 | Transport implementations should handle various error scenarios:
1212 |
1213 | Connection errors
1214 | Message parsing errors
1215 | Protocol errors
1216 | Network timeouts
1217 | Resource cleanup
1218 | Example error handling:
1219 |
1220 | TypeScript
1221 | Python
1222 |
1223 | class ExampleTransport implements Transport {
1224 | async start() {
1225 | try {
1226 | // Connection logic
1227 | } catch (error) {
1228 | this.onerror?.(new Error(`Failed to connect: ${error}`));
1229 | throw error;
1230 | }
1231 | }
1232 |
1233 | async send(message: JSONRPCMessage) {
1234 | try {
1235 | // Sending logic
1236 | } catch (error) {
1237 | this.onerror?.(new Error(`Failed to send message: ${error}`));
1238 | throw error;
1239 | }
1240 | }
1241 | }
1242 |
1243 | Best Practices
1244 | When implementing or using MCP transport:
1245 |
1246 | Handle connection lifecycle properly
1247 | Implement proper error handling
1248 | Clean up resources on connection close
1249 | Use appropriate timeouts
1250 | Validate messages before sending
1251 | Log transport events for debugging
1252 | Implement reconnection logic when appropriate
1253 | Handle backpressure in message queues
1254 | Monitor connection health
1255 | Implement proper security measures
1256 |
1257 | Security Considerations
1258 | When implementing transport:
1259 |
1260 |
1261 | Authentication and Authorization
1262 | Implement proper authentication mechanisms
1263 | Validate client credentials
1264 | Use secure token handling
1265 | Implement authorization checks
1266 |
1267 | Data Security
1268 | Use TLS for network transport
1269 | Encrypt sensitive data
1270 | Validate message integrity
1271 | Implement message size limits
1272 | Sanitize input data
1273 |
1274 | Network Security
1275 | Implement rate limiting
1276 | Use appropriate timeouts
1277 | Handle denial of service scenarios
1278 | Monitor for unusual patterns
1279 | Implement proper firewall rules
1280 |
1281 | Debugging Transport
1282 | Tips for debugging transport issues:
1283 |
1284 | Enable debug logging
1285 | Monitor message flow
1286 | Check connection states
1287 | Validate message formats
1288 | Test error scenarios
1289 | Use network analysis tools
1290 | Implement health checks
1291 | Monitor resource usage
1292 | Test edge cases
1293 | Use proper error tracking
1294 |
1295 | ###
1296 |
1297 | Here is information on MCP Sampling
1298 |
1299 | ###
1300 |
1301 | Sampling
1302 | Let your servers request completions from LLMs
1303 |
1304 | Sampling is a powerful MCP feature that allows servers to request LLM completions through the client, enabling sophisticated agentic behaviors while maintaining security and privacy.
1305 |
1306 | This feature of MCP is not yet supported in the Claude Desktop client.
1307 |
1308 |
1309 | How sampling works
1310 | The sampling flow follows these steps:
1311 |
1312 | Server sends a sampling/createMessage request to the client
1313 | Client reviews the request and can modify it
1314 | Client samples from an LLM
1315 | Client reviews the completion
1316 | Client returns the result to the server
1317 | This human-in-the-loop design ensures users maintain control over what the LLM sees and generates.
1318 |
1319 |
1320 | Message format
1321 | Sampling requests use a standardized message format:
1322 |
1323 | {
1324 | messages: [
1325 | {
1326 | role: "user" | "assistant",
1327 | content: {
1328 | type: "text" | "image",
1329 |
1330 | // For text:
1331 | text?: string,
1332 |
1333 | // For images:
1334 | data?: string, // base64 encoded
1335 | mimeType?: string
1336 | }
1337 | }
1338 |
1339 | ],
1340 | modelPreferences?: {
1341 | hints?: [{
1342 | name?: string // Suggested model name/family
1343 | }],
1344 | costPriority?: number, // 0-1, importance of minimizing cost
1345 | speedPriority?: number, // 0-1, importance of low latency
1346 | intelligencePriority?: number // 0-1, importance of capabilities
1347 | },
1348 | systemPrompt?: string,
1349 | includeContext?: "none" | "thisServer" | "allServers",
1350 | temperature?: number,
1351 | maxTokens: number,
1352 | stopSequences?: string[],
1353 | metadata?: Record<string, unknown>
1354 | }
1355 |
1356 | Request parameters
1357 |
1358 | Messages
1359 | The messages array contains the conversation history to send to the LLM. Each message has:
1360 |
1361 | role: Either “user” or “assistant”
1362 | content: The message content, which can be:
1363 | Text content with a text field
1364 | Image content with data (base64) and mimeType fields
1365 |
1366 | Model preferences
1367 | The modelPreferences object allows servers to specify their model selection preferences:
1368 |
1369 | hints: Array of model name suggestions that clients can use to select an appropriate model:
1370 |
1371 | name: String that can match full or partial model names (e.g. “claude-3”, “sonnet”)
1372 | Clients may map hints to equivalent models from different providers
1373 | Multiple hints are evaluated in preference order
1374 | Priority values (0-1 normalized):
1375 |
1376 | costPriority: Importance of minimizing costs
1377 | speedPriority: Importance of low latency response
1378 | intelligencePriority: Importance of advanced model capabilities
1379 | Clients make the final model selection based on these preferences and their available models.
1380 |
1381 |
1382 | System prompt
1383 | An optional systemPrompt field allows servers to request a specific system prompt. The client may modify or ignore this.
1384 |
1385 |
1386 | Context inclusion
1387 | The includeContext parameter specifies what MCP context to include:
1388 |
1389 | "none": No additional context
1390 | "thisServer": Include context from the requesting server
1391 | "allServers": Include context from all connected MCP servers
1392 | The client controls what context is actually included.
1393 |
1394 |
1395 | Sampling parameters
1396 | Fine-tune the LLM sampling with:
1397 |
1398 | temperature: Controls randomness (0.0 to 1.0)
1399 | maxTokens: Maximum tokens to generate
1400 | stopSequences: Array of sequences that stop generation
1401 | metadata: Additional provider-specific parameters
1402 |
1403 | Response format
1404 | The client returns a completion result:
1405 |
1406 | {
1407 | model: string, // Name of the model used
1408 | stopReason?: "endTurn" | "stopSequence" | "maxTokens" | string,
1409 | role: "user" | "assistant",
1410 | content: {
1411 | type: "text" | "image",
1412 | text?: string,
1413 | data?: string,
1414 | mimeType?: string
1415 | }
1416 | }
1417 |
1418 | Example request
1419 | Here’s an example of requesting sampling from a client:
1420 |
1421 | {
1422 | "method": "sampling/createMessage",
1423 | "params": {
1424 | "messages": [
1425 | {
1426 | "role": "user",
1427 | "content": {
1428 | "type": "text",
1429 | "text": "What files are in the current directory?"
1430 | }
1431 | }
1432 | ],
1433 | "systemPrompt": "You are a helpful file system assistant.",
1434 | "includeContext": "thisServer",
1435 | "maxTokens": 100
1436 | }
1437 | }
1438 |
1439 | Best practices
1440 | When implementing sampling:
1441 |
1442 | Always provide clear, well-structured prompts
1443 | Handle both text and image content appropriately
1444 | Set reasonable token limits
1445 | Include relevant context through includeContext
1446 | Validate responses before using them
1447 | Handle errors gracefully
1448 | Consider rate limiting sampling requests
1449 | Document expected sampling behavior
1450 | Test with various model parameters
1451 | Monitor sampling costs
1452 |
1453 | Human in the loop controls
1454 | Sampling is designed with human oversight in mind:
1455 |
1456 |
1457 | For prompts
1458 | Clients should show users the proposed prompt
1459 | Users should be able to modify or reject prompts
1460 | System prompts can be filtered or modified
1461 | Context inclusion is controlled by the client
1462 |
1463 | For completions
1464 | Clients should show users the completion
1465 | Users should be able to modify or reject completions
1466 | Clients can filter or modify completions
1467 | Users control which model is used
1468 |
1469 | Security considerations
1470 | When implementing sampling:
1471 |
1472 | Validate all message content
1473 | Sanitize sensitive information
1474 | Implement appropriate rate limits
1475 | Monitor sampling usage
1476 | Encrypt data in transit
1477 | Handle user data privacy
1478 | Audit sampling requests
1479 | Control cost exposure
1480 | Implement timeouts
1481 | Handle model errors gracefully
1482 |
1483 | Common patterns
1484 |
1485 | Agentic workflows
1486 | Sampling enables agentic patterns like:
1487 |
1488 | Reading and analyzing resources
1489 | Making decisions based on context
1490 | Generating structured data
1491 | Handling multi-step tasks
1492 | Providing interactive assistance
1493 |
1494 | Context management
1495 | Best practices for context:
1496 |
1497 | Request minimal necessary context
1498 | Structure context clearly
1499 | Handle context size limits
1500 | Update context as needed
1501 | Clean up stale context
1502 |
1503 | Error handling
1504 | Robust error handling should:
1505 |
1506 | Catch sampling failures
1507 | Handle timeout errors
1508 | Manage rate limits
1509 | Validate responses
1510 | Provide fallback behaviors
1511 | Log errors appropriately
1512 |
1513 | Limitations
1514 | Be aware of these limitations:
1515 |
1516 | Sampling depends on client capabilities
1517 | Users control sampling behavior
1518 | Context size has limits
1519 | Rate limits may apply
1520 | Costs should be considered
1521 | Model availability varies
1522 | Response times vary
1523 | Not all content types supported
1524 |
1525 | ###
1526 |
1527 | Here is information on building an MCP Server with Node
1528 |
1529 | ###
1530 |
1531 | Quickstart
1532 | For Server Developers
1533 | Get started building your own server to use in Claude for Desktop and other clients.
1534 |
1535 | In this tutorial, we’ll build a simple MCP weather server and connect it to a host, Claude for Desktop. We’ll start with a basic setup, and then progress to more complex use cases.
1536 |
1537 |
1538 | What we’ll be building
1539 | Many LLMs (including Claude) do not currently have the ability to fetch the forecast and severe weather alerts. Let’s use MCP to solve that!
1540 |
1541 | We’ll build a server that exposes two tools: get-alerts and get-forecast. Then we’ll connect the server to an MCP host (in this case, Claude for Desktop):
1542 |
1543 | Servers can connect to any client. We’ve chosen Claude for Desktop here for simplicity, but we also have guides on building your own client as well as a list of other clients here.
1544 |
1545 | Why Claude for Desktop and not Claude.ai?
1546 |
1547 |
1548 | Core MCP Concepts
1549 | MCP servers can provide three main types of capabilities:
1550 |
1551 | Resources: File-like data that can be read by clients (like API responses or file contents)
1552 | Tools: Functions that can be called by the LLM (with user approval)
1553 | Prompts: Pre-written templates that help users accomplish specific tasks
1554 | This tutorial will primarily focus on tools.
1555 |
1556 | Python
1557 | Node
1558 | Let’s get started with building our weather server! You can find the complete code for what we’ll be building here.
1559 |
1560 | Prerequisite knowledge
1561 | This quickstart assumes you have familiarity with:
1562 |
1563 | TypeScript
1564 | LLMs like Claude
1565 | System requirements
1566 | For TypeScript, make sure you have the latest version of Node installed.
1567 |
1568 | Set up your environment
1569 | First, let’s install Node.js and npm if you haven’t already. You can download them from nodejs.org. Verify your Node.js installation:
1570 |
1571 | node --version
1572 | npm --version
1573 | For this tutorial, you’ll need Node.js version 16 or higher.
1574 |
1575 | Now, let’s create and set up our project:
1576 |
1577 | MacOS/Linux
1578 |
1579 | Windows
1580 |
1581 | # Create a new directory for our project
1582 |
1583 | mkdir weather
1584 | cd weather
1585 |
1586 | # Initialize a new npm project
1587 |
1588 | npm init -y
1589 |
1590 | # Install dependencies
1591 |
1592 | npm install @modelcontextprotocol/sdk zod
1593 | npm install -D @types/node typescript
1594 |
1595 | # Create our files
1596 |
1597 | mkdir src
1598 | touch src/index.ts
1599 | Update your package.json to add type: “module” and a build script:
1600 |
1601 | package.json
1602 |
1603 | {
1604 | "type": "module",
1605 | "bin": {
1606 | "weather": "./build/index.js"
1607 | },
1608 | "scripts": {
1609 | "build": "tsc && node -e \"require('fs').chmodSync('build/index.js', '755')\"",
1610 | },
1611 | "files": [
1612 | "build"
1613 | ],
1614 | }
1615 | Create a tsconfig.json in the root of your project:
1616 |
1617 | tsconfig.json
1618 |
1619 | {
1620 | "compilerOptions": {
1621 | "target": "ES2022",
1622 | "module": "Node16",
1623 | "moduleResolution": "Node16",
1624 | "outDir": "./build",
1625 | "rootDir": "./src",
1626 | "strict": true,
1627 | "esModuleInterop": true,
1628 | "skipLibCheck": true,
1629 | "forceConsistentCasingInFileNames": true
1630 | },
1631 | "include": ["src/**/*"],
1632 | "exclude": ["node_modules"]
1633 | }
1634 | Now let’s dive into building your server.
1635 |
1636 | Building your server
1637 | Importing packages
1638 | Add these to the top of your src/index.ts:
1639 |
1640 | import { Server } from "@modelcontextprotocol/sdk/server/index.js";
1641 | import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
1642 | import {
1643 | CallToolRequestSchema,
1644 | ListToolsRequestSchema,
1645 | } from "@modelcontextprotocol/sdk/types.js";
1646 | import { z } from "zod";
1647 | Setting up the instance
1648 | Then initialize the NWS API base URL, validation schemas, and server instance:
1649 |
1650 | const NWS_API_BASE = "https://api.weather.gov";
1651 | const USER_AGENT = "weather-app/1.0";
1652 |
1653 | // Define Zod schemas for validation
1654 | const AlertsArgumentsSchema = z.object({
1655 | state: z.string().length(2),
1656 | });
1657 |
1658 | const ForecastArgumentsSchema = z.object({
1659 | latitude: z.number().min(-90).max(90),
1660 | longitude: z.number().min(-180).max(180),
1661 | });
1662 |
1663 | // Create server instance
1664 | const server = new Server(
1665 | {
1666 | name: "weather",
1667 | version: "1.0.0",
1668 | },
1669 | {
1670 | capabilities: {
1671 | tools: {},
1672 | },
1673 | }
1674 | );
1675 | Implementing tool listing
1676 | We need to tell clients what tools are available. This server.setRequestHandler call will register this list for us:
1677 |
1678 | // List available tools
1679 | server.setRequestHandler(ListToolsRequestSchema, async () => {
1680 | return {
1681 | tools: [
1682 | {
1683 | name: "get-alerts",
1684 | description: "Get weather alerts for a state",
1685 | inputSchema: {
1686 | type: "object",
1687 | properties: {
1688 | state: {
1689 | type: "string",
1690 | description: "Two-letter state code (e.g. CA, NY)",
1691 | },
1692 | },
1693 | required: ["state"],
1694 | },
1695 | },
1696 | {
1697 | name: "get-forecast",
1698 | description: "Get weather forecast for a location",
1699 | inputSchema: {
1700 | type: "object",
1701 | properties: {
1702 | latitude: {
1703 | type: "number",
1704 | description: "Latitude of the location",
1705 | },
1706 | longitude: {
1707 | type: "number",
1708 | description: "Longitude of the location",
1709 | },
1710 | },
1711 | required: ["latitude", "longitude"],
1712 | },
1713 | },
1714 | ],
1715 | };
1716 | });
1717 | This defines our two tools: get-alerts and get-forecast.
1718 |
1719 | Helper functions
1720 | Next, let’s add our helper functions for querying and formatting the data from the National Weather Service API:
1721 |
1722 | // Helper function for making NWS API requests
1723 | async function makeNWSRequest<T>(url: string): Promise<T | null> {
1724 | const headers = {
1725 | "User-Agent": USER_AGENT,
1726 | Accept: "application/geo+json",
1727 | };
1728 |
1729 | try {
1730 | const response = await fetch(url, { headers });
1731 | if (!response.ok) {
1732 | throw new Error(`HTTP error! status: ${response.status}`);
1733 | }
1734 | return (await response.json()) as T;
1735 | } catch (error) {
1736 | console.error("Error making NWS request:", error);
1737 | return null;
1738 | }
1739 | }
1740 |
1741 | interface AlertFeature {
1742 | properties: {
1743 | event?: string;
1744 | areaDesc?: string;
1745 | severity?: string;
1746 | status?: string;
1747 | headline?: string;
1748 | };
1749 | }
1750 |
1751 | // Format alert data
1752 | function formatAlert(feature: AlertFeature): string {
1753 | const props = feature.properties;
1754 | return [
1755 | `Event: ${props.event || "Unknown"}`,
1756 | `Area: ${props.areaDesc || "Unknown"}`,
1757 | `Severity: ${props.severity || "Unknown"}`,
1758 | `Status: ${props.status || "Unknown"}`,
1759 | `Headline: ${props.headline || "No headline"}`,
1760 | "---",
1761 | ].join("\n");
1762 | }
1763 |
1764 | interface ForecastPeriod {
1765 | name?: string;
1766 | temperature?: number;
1767 | temperatureUnit?: string;
1768 | windSpeed?: string;
1769 | windDirection?: string;
1770 | shortForecast?: string;
1771 | }
1772 |
1773 | interface AlertsResponse {
1774 | features: AlertFeature[];
1775 | }
1776 |
1777 | interface PointsResponse {
1778 | properties: {
1779 | forecast?: string;
1780 | };
1781 | }
1782 |
1783 | interface ForecastResponse {
1784 | properties: {
1785 | periods: ForecastPeriod[];
1786 | };
1787 | }
1788 | Implementing tool execution
1789 | The tool execution handler is responsible for actually executing the logic of each tool. Let’s add it:
1790 |
1791 | // Handle tool execution
1792 | server.setRequestHandler(CallToolRequestSchema, async (request) => {
1793 | const { name, arguments: args } = request.params;
1794 |
1795 | try {
1796 | if (name === "get-alerts") {
1797 | const { state } = AlertsArgumentsSchema.parse(args);
1798 | const stateCode = state.toUpperCase();
1799 |
1800 | const alertsUrl = `${NWS_API_BASE}/alerts?area=${stateCode}`;
1801 | const alertsData = await makeNWSRequest<AlertsResponse>(alertsUrl);
1802 |
1803 | if (!alertsData) {
1804 | return {
1805 | content: [
1806 | {
1807 | type: "text",
1808 | text: "Failed to retrieve alerts data",
1809 | },
1810 | ],
1811 | };
1812 | }
1813 |
1814 | const features = alertsData.features || [];
1815 | if (features.length === 0) {
1816 | return {
1817 | content: [
1818 | {
1819 | type: "text",
1820 | text: `No active alerts for ${stateCode}`,
1821 | },
1822 | ],
1823 | };
1824 | }
1825 |
1826 | const formattedAlerts = features.map(formatAlert).slice(0, 20) // only take the first 20 alerts;
1827 | const alertsText = `Active alerts for ${stateCode}:\n\n${formattedAlerts.join(
1828 | "\n"
1829 | )}`;
1830 |
1831 | return {
1832 | content: [
1833 | {
1834 | type: "text",
1835 | text: alertsText,
1836 | },
1837 | ],
1838 | };
1839 | } else if (name === "get-forecast") {
1840 | const { latitude, longitude } = ForecastArgumentsSchema.parse(args);
1841 |
1842 | // Get grid point data
1843 | const pointsUrl = `${NWS_API_BASE}/points/${latitude.toFixed(
1844 | 4
1845 | )},${longitude.toFixed(4)}`;
1846 | const pointsData = await makeNWSRequest<PointsResponse>(pointsUrl);
1847 |
1848 | if (!pointsData) {
1849 | return {
1850 | content: [
1851 | {
1852 | type: "text",
1853 | text: `Failed to retrieve grid point data for coordinates: ${latitude}, ${longitude}. This location may not be supported by the NWS API (only US locations are supported).`,
1854 | },
1855 | ],
1856 | };
1857 | }
1858 |
1859 | const forecastUrl = pointsData.properties?.forecast;
1860 | if (!forecastUrl) {
1861 | return {
1862 | content: [
1863 | {
1864 | type: "text",
1865 | text: "Failed to get forecast URL from grid point data",
1866 | },
1867 | ],
1868 | };
1869 | }
1870 |
1871 | // Get forecast data
1872 | const forecastData = await makeNWSRequest<ForecastResponse>(forecastUrl);
1873 | if (!forecastData) {
1874 | return {
1875 | content: [
1876 | {
1877 | type: "text",
1878 | text: "Failed to retrieve forecast data",
1879 | },
1880 | ],
1881 | };
1882 | }
1883 |
1884 | const periods = forecastData.properties?.periods || [];
1885 | if (periods.length === 0) {
1886 | return {
1887 | content: [
1888 | {
1889 | type: "text",
1890 | text: "No forecast periods available",
1891 | },
1892 | ],
1893 | };
1894 | }
1895 |
1896 | // Format forecast periods
1897 | const formattedForecast = periods.map((period: ForecastPeriod) =>
1898 | [
1899 | `${period.name || "Unknown"}:`,
1900 | `Temperature: ${period.temperature || "Unknown"}°${
1901 | period.temperatureUnit || "F"
1902 | }`,
1903 | `Wind: ${period.windSpeed || "Unknown"} ${
1904 | period.windDirection || ""
1905 | }`,
1906 | `${period.shortForecast || "No forecast available"}`,
1907 | "---",
1908 | ].join("\n")
1909 | );
1910 |
1911 | const forecastText = `Forecast for ${latitude}, ${longitude}:\n\n${formattedForecast.join(
1912 | "\n"
1913 | )}`;
1914 |
1915 | return {
1916 | content: [
1917 | {
1918 | type: "text",
1919 | text: forecastText,
1920 | },
1921 | ],
1922 | };
1923 | } else {
1924 | throw new Error(`Unknown tool: ${name}`);
1925 | }
1926 |
1927 | } catch (error) {
1928 | if (error instanceof z.ZodError) {
1929 | throw new Error(
1930 | `Invalid arguments: ${error.errors
1931 | .map((e) => `${e.path.join(".")}: ${e.message}`)
1932 | .join(", ")}`
1933 | );
1934 | }
1935 | throw error;
1936 | }
1937 | });
1938 | Running the server
1939 | Finally, implement the main function to run the server:
1940 |
1941 | // Start the server
1942 | async function main() {
1943 | const transport = new StdioServerTransport();
1944 | await server.connect(transport);
1945 | console.error("Weather MCP Server running on stdio");
1946 | }
1947 |
1948 | main().catch((error) => {
1949 | console.error("Fatal error in main():", error);
1950 | process.exit(1);
1951 | });
1952 | Make sure to run npm run build to build your server! This is a very important step in getting your server to connect.
1953 |
1954 | Let’s now test your server from an existing MCP host, Claude for Desktop.
1955 |
1956 | Testing your server with Claude for Desktop
1957 | Claude for Desktop is not yet available on Linux. Linux users can proceed to the Building a client tutorial to build an MCP client that connects to the server we just built.
1958 |
1959 | First, make sure you have Claude for Desktop installed. You can install the latest version here. If you already have Claude for Desktop, make sure it’s updated to the latest version.
1960 |
1961 | We’ll need to configure Claude for Desktop for whichever MCP servers you want to use. To do this, open your Claude for Desktop App configuration at ~/Library/Application Support/Claude/claude_desktop_config.json in a text editor. Make sure to create the file if it doesn’t exist.
1962 |
1963 | For example, if you have VS Code installed:
1964 |
1965 | MacOS/Linux
1966 | Windows
1967 |
1968 | code ~/Library/Application\ Support/Claude/claude_desktop_config.json
1969 | You’ll then add your servers in the mcpServers key. The MCP UI elements will only show up in Claude for Desktop if at least one server is properly configured.
1970 |
1971 | In this case, we’ll add our single weather server like so:
1972 |
1973 | MacOS/Linux
1974 | Windows
1975 |
1976 | Node
1977 |
1978 | {
1979 | "mcpServers": {
1980 | "weather": {
1981 | "command": "node",
1982 | "args": [
1983 | "/ABSOLUTE/PATH/TO/PARENT/FOLDER/weather/build/index.js"
1984 | ]
1985 | }
1986 | }
1987 | }
1988 | This tells Claude for Desktop:
1989 |
1990 | There’s an MCP server named “weather”
1991 | Launch it by running node /ABSOLUTE/PATH/TO/PARENT/FOLDER/weather/build/index.js
1992 | Save the file, and restart Claude for Desktop.
1993 |
1994 |
1995 | Test with commands
1996 | Let’s make sure Claude for Desktop is picking up the two tools we’ve exposed in our weather server. You can do this by looking for the hammer icon:
1997 |
1998 | After clicking on the hammer icon, you should see two tools listed:
1999 |
2000 | If your server isn’t being picked up by Claude for Desktop, proceed to the Troubleshooting section for debugging tips.
2001 |
2002 | If the hammer icon has shown up, you can now test your server by running the following commands in Claude for Desktop:
2003 |
2004 | What’s the weather in Sacramento?
2005 | What are the active weather alerts in Texas?
2006 |
2007 | Since this is the US National Weather service, the queries will only work for US locations.
2008 |
2009 |
2010 | What’s happening under the hood
2011 | When you ask a question:
2012 |
2013 | The client sends your question to Claude
2014 | Claude analyzes the available tools and decides which one(s) to use
2015 | The client executes the chosen tool(s) through the MCP server
2016 | The results are sent back to Claude
2017 | Claude formulates a natural language response
2018 | The response is displayed to you!
2019 |
2020 | ###
2021 |
```