@diffra-ai/cli 0.2.1 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/bundle/chunks/{anthropic-messages-UM2LSKVG.js → anthropic-messages-VPHYDMHB.js} +1 -1
  3. package/dist/bundle/chunks/{azure-openai-responses-LLULQ6UR.js → azure-openai-responses-JYJ2VXQ2.js} +1 -1
  4. package/dist/bundle/chunks/bedrock-converse-stream.js +1 -1
  5. package/dist/bundle/chunks/{chunk-I6QEKFFB.js → chunk-2IABWVGX.js} +1 -1
  6. package/dist/bundle/chunks/{chunk-6NW7EDTU.js → chunk-6RV2XP5B.js} +6 -6
  7. package/dist/bundle/chunks/{chunk-Y5LGEDHU.js → chunk-FCSMMPE4.js} +1 -1
  8. package/dist/bundle/chunks/{chunk-MAMCTGRH.js → chunk-JEYYTVUX.js} +1 -1
  9. package/dist/bundle/chunks/chunk-NPHITI73.js +30 -0
  10. package/dist/bundle/chunks/{chunk-UBBD6YWP.js → chunk-QQYLP3HG.js} +1 -1
  11. package/dist/bundle/chunks/{chunk-J2CQ7AOB.js → chunk-QY4GYLLA.js} +1 -1
  12. package/dist/bundle/chunks/{chunk-MWJ5PWKE.js → chunk-REVASUCD.js} +1 -1
  13. package/dist/bundle/chunks/{chunk-BSCVN57O.js → chunk-S7OTLWTF.js} +1 -1
  14. package/dist/bundle/chunks/{chunk-QCEU5NDS.js → chunk-TOBZDLTR.js} +1 -1
  15. package/dist/bundle/chunks/{chunk-37INV3TW.js → chunk-Z4BBBJG4.js} +1 -1
  16. package/dist/bundle/chunks/{cli-VEFNOOXB.js → cli-I4RCHKMY.js} +1 -1
  17. package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-VQHACWH5.js → cloudflare-workers-ai-system-one-OTYUASP3.js} +1 -1
  18. package/dist/bundle/chunks/github-copilot.js +1 -1
  19. package/dist/bundle/chunks/{google-generative-ai-YFRD2UAD.js → google-generative-ai-DI3FOC25.js} +1 -1
  20. package/dist/bundle/chunks/{google-vertex-7EWCT4BL.js → google-vertex-VBHHROPU.js} +1 -1
  21. package/dist/bundle/chunks/{llama-cpp-classify-D5PC6EEP.js → llama-cpp-classify-MUFWIFOW.js} +1 -1
  22. package/dist/bundle/chunks/{mistral-conversations-ILNLXCLF.js → mistral-conversations-Q2PGF352.js} +1 -1
  23. package/dist/bundle/chunks/{openai-codex-responses-YESP5ZRN.js → openai-codex-responses-WWZAXEPG.js} +1 -1
  24. package/dist/bundle/chunks/{openai-completions-BKYCRYVB.js → openai-completions-4C7QTL2T.js} +1 -1
  25. package/dist/bundle/chunks/{openai-decisions-OZVDLRU3.js → openai-decisions-NYOT2XIF.js} +1 -1
  26. package/dist/bundle/chunks/{openai-responses-GSXMBGMK.js → openai-responses-R5MW34FB.js} +1 -1
  27. package/dist/bundle/chunks/{openrouter-images-TK5PJTOE.js → openrouter-images-FBKW4PD4.js} +1 -1
  28. package/dist/bundle/chunks/{pi-messages-AHAEGVU4.js → pi-messages-LJZPZBQY.js} +1 -1
  29. package/dist/bundle/chunks/{typesafe-system-one-XHINCFVH.js → typesafe-system-one-7MCWBLJY.js} +1 -1
  30. package/dist/bundle/chunks/{virtual-modules-7F3I52A6.js → virtual-modules-J4Z2IMRZ.js} +1 -1
  31. package/dist/bundle/cli-runtime.js +1 -1
  32. package/dist/bundle/cli.js +0 -0
  33. package/dist/bundle/index.js +1 -1
  34. package/dist/bundle/rpc-entry.js +1 -1
  35. package/dist/cli.js +0 -0
  36. package/dist/core/model-resolver.js +3 -3
  37. package/dist/core/model-resolver.js.map +1 -1
  38. package/dist/extensions/skills/bundled/find-skills/LICENSE +21 -0
  39. package/dist/extensions/skills/bundled/find-skills/SKILL.md +117 -0
  40. package/dist/extensions/skills/bundled/grill-me/LICENSE +21 -0
  41. package/dist/extensions/skills/bundled/grill-me/SKILL.md +44 -0
  42. package/dist/extensions/skills/bundled/handoff/LICENSE +21 -0
  43. package/dist/extensions/skills/bundled/handoff/SKILL.md +31 -0
  44. package/dist/extensions/skills/bundled/mcp-builder/LICENSE.txt +202 -0
  45. package/dist/extensions/skills/bundled/mcp-builder/SKILL.md +260 -0
  46. package/dist/extensions/skills/bundled/mcp-builder/reference/evaluation.md +432 -0
  47. package/dist/extensions/skills/bundled/mcp-builder/reference/mcp_best_practices.md +249 -0
  48. package/dist/extensions/skills/bundled/mcp-builder/reference/node_mcp_server.md +972 -0
  49. package/dist/extensions/skills/bundled/mcp-builder/reference/node_mcp_server_v2.md +747 -0
  50. package/dist/extensions/skills/bundled/mcp-builder/reference/python_mcp_server.md +719 -0
  51. package/dist/extensions/skills/bundled/ui-ux-pro-max/LICENSE +21 -0
  52. package/dist/extensions/skills/bundled/ui-ux-pro-max/SKILL.md +251 -0
  53. package/dist/extensions/skills/bundled/ui-ux-pro-max/data/app-interface.csv +33 -0
  54. package/dist/extensions/skills/bundled/ui-ux-pro-max/data/charts.csv +26 -0
  55. package/dist/extensions/skills/bundled/ui-ux-pro-max/data/colors.csv +195 -0
  56. package/dist/extensions/skills/bundled/ui-ux-pro-max/data/google-fonts.csv +1935 -0
  57. package/dist/extensions/skills/bundled/ui-ux-pro-max/data/icons.csv +106 -0
  58. package/dist/extensions/skills/bundled/ui-ux-pro-max/data/landing.csv +35 -0
  59. package/dist/extensions/skills/bundled/ui-ux-pro-max/data/motion.csv +21 -0
  60. package/dist/extensions/skills/bundled/ui-ux-pro-max/data/products.csv +195 -0
  61. package/dist/extensions/skills/bundled/ui-ux-pro-max/data/react-performance.csv +45 -0
  62. package/dist/extensions/skills/bundled/ui-ux-pro-max/data/stacks/angular.csv +51 -0
  63. package/dist/extensions/skills/bundled/ui-ux-pro-max/data/stacks/astro.csv +54 -0
  64. package/dist/extensions/skills/bundled/ui-ux-pro-max/data/stacks/avalonia.csv +57 -0
  65. package/dist/extensions/skills/bundled/ui-ux-pro-max/data/stacks/flutter.csv +53 -0
  66. package/dist/extensions/skills/bundled/ui-ux-pro-max/data/stacks/html-tailwind.csv +60 -0
  67. package/dist/extensions/skills/bundled/ui-ux-pro-max/data/stacks/javafx.csv +76 -0
  68. package/dist/extensions/skills/bundled/ui-ux-pro-max/data/stacks/jetpack-compose.csv +53 -0
  69. package/dist/extensions/skills/bundled/ui-ux-pro-max/data/stacks/laravel.csv +51 -0
  70. package/dist/extensions/skills/bundled/ui-ux-pro-max/data/stacks/nextjs.csv +62 -0
  71. package/dist/extensions/skills/bundled/ui-ux-pro-max/data/stacks/nuxt-ui.csv +84 -0
  72. package/dist/extensions/skills/bundled/ui-ux-pro-max/data/stacks/nuxtjs.csv +68 -0
  73. package/dist/extensions/skills/bundled/ui-ux-pro-max/data/stacks/pyside6-qss.csv +103 -0
  74. package/dist/extensions/skills/bundled/ui-ux-pro-max/data/stacks/react-native.csv +52 -0
  75. package/dist/extensions/skills/bundled/ui-ux-pro-max/data/stacks/react.csv +67 -0
  76. package/dist/extensions/skills/bundled/ui-ux-pro-max/data/stacks/shadcn.csv +69 -0
  77. package/dist/extensions/skills/bundled/ui-ux-pro-max/data/stacks/svelte.csv +56 -0
  78. package/dist/extensions/skills/bundled/ui-ux-pro-max/data/stacks/swiftui.csv +51 -0
  79. package/dist/extensions/skills/bundled/ui-ux-pro-max/data/stacks/threejs.csv +54 -0
  80. package/dist/extensions/skills/bundled/ui-ux-pro-max/data/stacks/uno.csv +60 -0
  81. package/dist/extensions/skills/bundled/ui-ux-pro-max/data/stacks/uwp.csv +56 -0
  82. package/dist/extensions/skills/bundled/ui-ux-pro-max/data/stacks/vue.csv +50 -0
  83. package/dist/extensions/skills/bundled/ui-ux-pro-max/data/stacks/winui.csv +60 -0
  84. package/dist/extensions/skills/bundled/ui-ux-pro-max/data/stacks/wpf.csv +57 -0
  85. package/dist/extensions/skills/bundled/ui-ux-pro-max/data/styles.csv +90 -0
  86. package/dist/extensions/skills/bundled/ui-ux-pro-max/data/typography.csv +75 -0
  87. package/dist/extensions/skills/bundled/ui-ux-pro-max/data/ui-reasoning.csv +195 -0
  88. package/dist/extensions/skills/bundled/ui-ux-pro-max/data/ux-guidelines.csv +142 -0
  89. package/dist/extensions/skills/bundled/ui-ux-pro-max/references/pro-rules.md +117 -0
  90. package/dist/extensions/skills/bundled/ui-ux-pro-max/references/quick-reference.md +275 -0
  91. package/dist/extensions/skills/bundled/ui-ux-pro-max/scripts/core.py +1111 -0
  92. package/dist/extensions/skills/bundled/ui-ux-pro-max/scripts/design_system.py +1922 -0
  93. package/dist/extensions/skills/bundled/ui-ux-pro-max/scripts/preview.py +557 -0
  94. package/dist/extensions/skills/bundled/ui-ux-pro-max/scripts/reasoning_contract.py +123 -0
  95. package/dist/extensions/skills/bundled/ui-ux-pro-max/scripts/search.py +257 -0
  96. package/dist/extensions/skills/index.d.ts +4 -4
  97. package/dist/extensions/skills/index.d.ts.map +1 -1
  98. package/dist/extensions/skills/index.js +9 -4
  99. package/dist/extensions/skills/index.js.map +1 -1
  100. package/dist/rpc-entry.js +0 -0
  101. package/docs/builtin-skills.md +46 -3
  102. package/docs/docs.json +1 -1
  103. package/docs/skills.md +1 -1
  104. package/docs/slash-commands.md +2 -0
  105. package/examples/extensions/doom-overlay/doom/build/doom.wasm +0 -0
  106. package/examples/extensions/doom-overlay/doom/build.sh +0 -0
  107. package/package.json +6 -6
  108. package/dist/bundle/chunks/chunk-UIVU7TEF.js +0 -30
@@ -0,0 +1,972 @@
1
+ # Node/TypeScript MCP Server Implementation Guide
2
+
3
+ > **This guide covers v1 of the TypeScript SDK (`@modelcontextprotocol/sdk`).** Use it only for projects that already depend on v1. For new servers, use the [v2 guide](./node_mcp_server_v2.md).
4
+
5
+ ## Overview
6
+
7
+ This document provides Node/TypeScript-specific best practices and examples for implementing MCP servers using the MCP TypeScript SDK. It covers project structure, server setup, tool registration patterns, input validation with Zod, error handling, and complete working examples.
8
+
9
+ ---
10
+
11
+ ## Quick Reference
12
+
13
+ ### Key Imports
14
+ ```typescript
15
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
16
+ import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
17
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
18
+ import express from "express";
19
+ import { z } from "zod";
20
+ ```
21
+
22
+ ### Server Initialization
23
+ ```typescript
24
+ const server = new McpServer({
25
+ name: "service-mcp-server",
26
+ version: "1.0.0"
27
+ });
28
+ ```
29
+
30
+ ### Tool Registration Pattern
31
+ ```typescript
32
+ server.registerTool(
33
+ "tool_name",
34
+ {
35
+ title: "Tool Display Name",
36
+ description: "What the tool does",
37
+ inputSchema: { param: z.string() },
38
+ outputSchema: { result: z.string() }
39
+ },
40
+ async ({ param }) => {
41
+ const output = { result: `Processed: ${param}` };
42
+ return {
43
+ content: [{ type: "text", text: JSON.stringify(output) }],
44
+ structuredContent: output // Modern pattern for structured data
45
+ };
46
+ }
47
+ );
48
+ ```
49
+
50
+ ---
51
+
52
+ ## MCP TypeScript SDK
53
+
54
+ The official MCP TypeScript SDK provides:
55
+ - `McpServer` class for server initialization
56
+ - `registerTool` method for tool registration
57
+ - Zod schema integration for runtime input validation
58
+ - Type-safe tool handler implementations
59
+
60
+ **IMPORTANT - Use Modern APIs Only:**
61
+ - **DO use**: `server.registerTool()`, `server.registerResource()`, `server.registerPrompt()`
62
+ - **DO NOT use**: Old deprecated APIs such as `server.tool()`, `server.setRequestHandler(ListToolsRequestSchema, ...)`, or manual handler registration
63
+ - The `register*` methods provide better type safety, automatic schema handling, and are the recommended approach
64
+
65
+ See the MCP SDK documentation in the references for complete details.
66
+
67
+ ## Server Naming Convention
68
+
69
+ Node/TypeScript MCP servers must follow this naming pattern:
70
+ - **Format**: `{service}-mcp-server` (lowercase with hyphens)
71
+ - **Examples**: `github-mcp-server`, `jira-mcp-server`, `stripe-mcp-server`
72
+
73
+ The name should be:
74
+ - General (not tied to specific features)
75
+ - Descriptive of the service/API being integrated
76
+ - Easy to infer from the task description
77
+ - Without version numbers or dates
78
+
79
+ ## Project Structure
80
+
81
+ Create the following structure for Node/TypeScript MCP servers:
82
+
83
+ ```
84
+ {service}-mcp-server/
85
+ ├── package.json
86
+ ├── tsconfig.json
87
+ ├── README.md
88
+ ├── src/
89
+ │ ├── index.ts # Main entry point with McpServer initialization
90
+ │ ├── types.ts # TypeScript type definitions and interfaces
91
+ │ ├── tools/ # Tool implementations (one file per domain)
92
+ │ ├── services/ # API clients and shared utilities
93
+ │ ├── schemas/ # Zod validation schemas
94
+ │ └── constants.ts # Shared constants (API_URL, CHARACTER_LIMIT, etc.)
95
+ └── dist/ # Built JavaScript files (entry point: dist/index.js)
96
+ ```
97
+
98
+ ## Tool Implementation
99
+
100
+ ### Tool Naming
101
+
102
+ Use snake_case for tool names (e.g., "search_users", "create_project", "get_channel_info") with clear, action-oriented names.
103
+
104
+ **Avoid Naming Conflicts**: Include the service context to prevent overlaps:
105
+ - Use "slack_send_message" instead of just "send_message"
106
+ - Use "github_create_issue" instead of just "create_issue"
107
+ - Use "asana_list_tasks" instead of just "list_tasks"
108
+
109
+ ### Tool Structure
110
+
111
+ Tools are registered using the `registerTool` method with the following requirements:
112
+ - Use Zod schemas for runtime input validation and type safety
113
+ - The `description` field must be explicitly provided - JSDoc comments are NOT automatically extracted
114
+ - Explicitly provide `title`, `description`, `inputSchema`, and `annotations`
115
+ - The `inputSchema` must be a Zod schema object (not a JSON schema)
116
+ - Type all parameters and return values explicitly
117
+
118
+ ```typescript
119
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
120
+ import { z } from "zod";
121
+
122
+ const server = new McpServer({
123
+ name: "example-mcp",
124
+ version: "1.0.0"
125
+ });
126
+
127
+ // Zod schema for input validation
128
+ const UserSearchInputSchema = z.object({
129
+ query: z.string()
130
+ .min(2, "Query must be at least 2 characters")
131
+ .max(200, "Query must not exceed 200 characters")
132
+ .describe("Search string to match against names/emails"),
133
+ limit: z.number()
134
+ .int()
135
+ .min(1)
136
+ .max(100)
137
+ .default(20)
138
+ .describe("Maximum results to return"),
139
+ offset: z.number()
140
+ .int()
141
+ .min(0)
142
+ .default(0)
143
+ .describe("Number of results to skip for pagination"),
144
+ response_format: z.nativeEnum(ResponseFormat)
145
+ .default(ResponseFormat.MARKDOWN)
146
+ .describe("Output format: 'markdown' for human-readable or 'json' for machine-readable")
147
+ }).strict();
148
+
149
+ // Type definition from Zod schema
150
+ type UserSearchInput = z.infer<typeof UserSearchInputSchema>;
151
+
152
+ server.registerTool(
153
+ "example_search_users",
154
+ {
155
+ title: "Search Example Users",
156
+ description: `Search for users in the Example system by name, email, or team.
157
+
158
+ This tool searches across all user profiles in the Example platform, supporting partial matches and various search filters. It does NOT create or modify users, only searches existing ones.
159
+
160
+ Args:
161
+ - query (string): Search string to match against names/emails
162
+ - limit (number): Maximum results to return, between 1-100 (default: 20)
163
+ - offset (number): Number of results to skip for pagination (default: 0)
164
+ - response_format ('markdown' | 'json'): Output format (default: 'markdown')
165
+
166
+ Returns:
167
+ For JSON format: Structured data with schema:
168
+ {
169
+ "total": number, // Total number of matches found
170
+ "count": number, // Number of results in this response
171
+ "offset": number, // Current pagination offset
172
+ "users": [
173
+ {
174
+ "id": string, // User ID (e.g., "U123456789")
175
+ "name": string, // Full name (e.g., "John Doe")
176
+ "email": string, // Email address
177
+ "team": string, // Team name (optional)
178
+ "active": boolean // Whether user is active
179
+ }
180
+ ],
181
+ "has_more": boolean, // Whether more results are available
182
+ "next_offset": number // Offset for next page (if has_more is true)
183
+ }
184
+
185
+ Examples:
186
+ - Use when: "Find all marketing team members" -> params with query="team:marketing"
187
+ - Use when: "Search for John's account" -> params with query="john"
188
+ - Don't use when: You need to create a user (use example_create_user instead)
189
+
190
+ Error Handling:
191
+ - Returns "Error: Rate limit exceeded" if too many requests (429 status)
192
+ - Returns "No users found matching '<query>'" if search returns empty`,
193
+ inputSchema: UserSearchInputSchema,
194
+ annotations: {
195
+ readOnlyHint: true,
196
+ destructiveHint: false,
197
+ idempotentHint: true,
198
+ openWorldHint: true
199
+ }
200
+ },
201
+ async (params: UserSearchInput) => {
202
+ try {
203
+ // Input validation is handled by Zod schema
204
+ // Make API request using validated parameters
205
+ const data = await makeApiRequest<any>(
206
+ "users/search",
207
+ "GET",
208
+ undefined,
209
+ {
210
+ q: params.query,
211
+ limit: params.limit,
212
+ offset: params.offset
213
+ }
214
+ );
215
+
216
+ const users = data.users || [];
217
+ const total = data.total || 0;
218
+
219
+ if (!users.length) {
220
+ return {
221
+ content: [{
222
+ type: "text",
223
+ text: `No users found matching '${params.query}'`
224
+ }]
225
+ };
226
+ }
227
+
228
+ // Prepare structured output
229
+ const output = {
230
+ total,
231
+ count: users.length,
232
+ offset: params.offset,
233
+ users: users.map((user: any) => ({
234
+ id: user.id,
235
+ name: user.name,
236
+ email: user.email,
237
+ ...(user.team ? { team: user.team } : {}),
238
+ active: user.active ?? true
239
+ })),
240
+ has_more: total > params.offset + users.length,
241
+ ...(total > params.offset + users.length ? {
242
+ next_offset: params.offset + users.length
243
+ } : {})
244
+ };
245
+
246
+ // Format text representation based on requested format
247
+ let textContent: string;
248
+ if (params.response_format === ResponseFormat.MARKDOWN) {
249
+ const lines = [`# User Search Results: '${params.query}'`, "",
250
+ `Found ${total} users (showing ${users.length})`, ""];
251
+ for (const user of users) {
252
+ lines.push(`## ${user.name} (${user.id})`);
253
+ lines.push(`- **Email**: ${user.email}`);
254
+ if (user.team) lines.push(`- **Team**: ${user.team}`);
255
+ lines.push("");
256
+ }
257
+ textContent = lines.join("\n");
258
+ } else {
259
+ textContent = JSON.stringify(output, null, 2);
260
+ }
261
+
262
+ return {
263
+ content: [{ type: "text", text: textContent }],
264
+ structuredContent: output // Modern pattern for structured data
265
+ };
266
+ } catch (error) {
267
+ return {
268
+ content: [{
269
+ type: "text",
270
+ text: handleApiError(error)
271
+ }]
272
+ };
273
+ }
274
+ }
275
+ );
276
+ ```
277
+
278
+ ## Zod Schemas for Input Validation
279
+
280
+ Zod provides runtime type validation:
281
+
282
+ ```typescript
283
+ import { z } from "zod";
284
+
285
+ // Basic schema with validation
286
+ const CreateUserSchema = z.object({
287
+ name: z.string()
288
+ .min(1, "Name is required")
289
+ .max(100, "Name must not exceed 100 characters"),
290
+ email: z.string()
291
+ .email("Invalid email format"),
292
+ age: z.number()
293
+ .int("Age must be a whole number")
294
+ .min(0, "Age cannot be negative")
295
+ .max(150, "Age cannot be greater than 150")
296
+ }).strict(); // Use .strict() to forbid extra fields
297
+
298
+ // Enums
299
+ enum ResponseFormat {
300
+ MARKDOWN = "markdown",
301
+ JSON = "json"
302
+ }
303
+
304
+ const SearchSchema = z.object({
305
+ response_format: z.nativeEnum(ResponseFormat)
306
+ .default(ResponseFormat.MARKDOWN)
307
+ .describe("Output format")
308
+ });
309
+
310
+ // Optional fields with defaults
311
+ const PaginationSchema = z.object({
312
+ limit: z.number()
313
+ .int()
314
+ .min(1)
315
+ .max(100)
316
+ .default(20)
317
+ .describe("Maximum results to return"),
318
+ offset: z.number()
319
+ .int()
320
+ .min(0)
321
+ .default(0)
322
+ .describe("Number of results to skip")
323
+ });
324
+ ```
325
+
326
+ ## Response Format Options
327
+
328
+ Support multiple output formats for flexibility:
329
+
330
+ ```typescript
331
+ enum ResponseFormat {
332
+ MARKDOWN = "markdown",
333
+ JSON = "json"
334
+ }
335
+
336
+ const inputSchema = z.object({
337
+ query: z.string(),
338
+ response_format: z.nativeEnum(ResponseFormat)
339
+ .default(ResponseFormat.MARKDOWN)
340
+ .describe("Output format: 'markdown' for human-readable or 'json' for machine-readable")
341
+ });
342
+ ```
343
+
344
+ **Markdown format**:
345
+ - Use headers, lists, and formatting for clarity
346
+ - Convert timestamps to human-readable format
347
+ - Show display names with IDs in parentheses
348
+ - Omit verbose metadata
349
+ - Group related information logically
350
+
351
+ **JSON format**:
352
+ - Return complete, structured data suitable for programmatic processing
353
+ - Include all available fields and metadata
354
+ - Use consistent field names and types
355
+
356
+ ## Pagination Implementation
357
+
358
+ For tools that list resources:
359
+
360
+ ```typescript
361
+ const ListSchema = z.object({
362
+ limit: z.number().int().min(1).max(100).default(20),
363
+ offset: z.number().int().min(0).default(0)
364
+ });
365
+
366
+ async function listItems(params: z.infer<typeof ListSchema>) {
367
+ const data = await apiRequest(params.limit, params.offset);
368
+
369
+ const response = {
370
+ total: data.total,
371
+ count: data.items.length,
372
+ offset: params.offset,
373
+ items: data.items,
374
+ has_more: data.total > params.offset + data.items.length,
375
+ next_offset: data.total > params.offset + data.items.length
376
+ ? params.offset + data.items.length
377
+ : undefined
378
+ };
379
+
380
+ return JSON.stringify(response, null, 2);
381
+ }
382
+ ```
383
+
384
+ ## Character Limits and Truncation
385
+
386
+ Add a CHARACTER_LIMIT constant to prevent overwhelming responses:
387
+
388
+ ```typescript
389
+ // At module level in constants.ts
390
+ export const CHARACTER_LIMIT = 25000; // Maximum response size in characters
391
+
392
+ async function searchTool(params: SearchInput) {
393
+ let result = generateResponse(data);
394
+
395
+ // Check character limit and truncate if needed
396
+ if (result.length > CHARACTER_LIMIT) {
397
+ const truncatedData = data.slice(0, Math.max(1, data.length / 2));
398
+ response.data = truncatedData;
399
+ response.truncated = true;
400
+ response.truncation_message =
401
+ `Response truncated from ${data.length} to ${truncatedData.length} items. ` +
402
+ `Use 'offset' parameter or add filters to see more results.`;
403
+ result = JSON.stringify(response, null, 2);
404
+ }
405
+
406
+ return result;
407
+ }
408
+ ```
409
+
410
+ ## Error Handling
411
+
412
+ Provide clear, actionable error messages:
413
+
414
+ ```typescript
415
+ import axios, { AxiosError } from "axios";
416
+
417
+ function handleApiError(error: unknown): string {
418
+ if (error instanceof AxiosError) {
419
+ if (error.response) {
420
+ switch (error.response.status) {
421
+ case 404:
422
+ return "Error: Resource not found. Please check the ID is correct.";
423
+ case 403:
424
+ return "Error: Permission denied. You don't have access to this resource.";
425
+ case 429:
426
+ return "Error: Rate limit exceeded. Please wait before making more requests.";
427
+ default:
428
+ return `Error: API request failed with status ${error.response.status}`;
429
+ }
430
+ } else if (error.code === "ECONNABORTED") {
431
+ return "Error: Request timed out. Please try again.";
432
+ }
433
+ }
434
+ return `Error: Unexpected error occurred: ${error instanceof Error ? error.message : String(error)}`;
435
+ }
436
+ ```
437
+
438
+ ## Shared Utilities
439
+
440
+ Extract common functionality into reusable functions:
441
+
442
+ ```typescript
443
+ // Shared API request function
444
+ async function makeApiRequest<T>(
445
+ endpoint: string,
446
+ method: "GET" | "POST" | "PUT" | "DELETE" = "GET",
447
+ data?: any,
448
+ params?: any
449
+ ): Promise<T> {
450
+ try {
451
+ const response = await axios({
452
+ method,
453
+ url: `${API_BASE_URL}/${endpoint}`,
454
+ data,
455
+ params,
456
+ timeout: 30000,
457
+ headers: {
458
+ "Content-Type": "application/json",
459
+ "Accept": "application/json"
460
+ }
461
+ });
462
+ return response.data;
463
+ } catch (error) {
464
+ throw error;
465
+ }
466
+ }
467
+ ```
468
+
469
+ ## Async/Await Best Practices
470
+
471
+ Always use async/await for network requests and I/O operations:
472
+
473
+ ```typescript
474
+ // Good: Async network request
475
+ async function fetchData(resourceId: string): Promise<ResourceData> {
476
+ const response = await axios.get(`${API_URL}/resource/${resourceId}`);
477
+ return response.data;
478
+ }
479
+
480
+ // Bad: Promise chains
481
+ function fetchData(resourceId: string): Promise<ResourceData> {
482
+ return axios.get(`${API_URL}/resource/${resourceId}`)
483
+ .then(response => response.data); // Harder to read and maintain
484
+ }
485
+ ```
486
+
487
+ ## TypeScript Best Practices
488
+
489
+ 1. **Use Strict TypeScript**: Enable strict mode in tsconfig.json
490
+ 2. **Define Interfaces**: Create clear interface definitions for all data structures
491
+ 3. **Avoid `any`**: Use proper types or `unknown` instead of `any`
492
+ 4. **Zod for Runtime Validation**: Use Zod schemas to validate external data
493
+ 5. **Type Guards**: Create type guard functions for complex type checking
494
+ 6. **Error Handling**: Always use try-catch with proper error type checking
495
+ 7. **Null Safety**: Use optional chaining (`?.`) and nullish coalescing (`??`)
496
+
497
+ ```typescript
498
+ // Good: Type-safe with Zod and interfaces
499
+ interface UserResponse {
500
+ id: string;
501
+ name: string;
502
+ email: string;
503
+ team?: string;
504
+ active: boolean;
505
+ }
506
+
507
+ const UserSchema = z.object({
508
+ id: z.string(),
509
+ name: z.string(),
510
+ email: z.string().email(),
511
+ team: z.string().optional(),
512
+ active: z.boolean()
513
+ });
514
+
515
+ type User = z.infer<typeof UserSchema>;
516
+
517
+ async function getUser(id: string): Promise<User> {
518
+ const data = await apiCall(`/users/${id}`);
519
+ return UserSchema.parse(data); // Runtime validation
520
+ }
521
+
522
+ // Bad: Using any
523
+ async function getUser(id: string): Promise<any> {
524
+ return await apiCall(`/users/${id}`); // No type safety
525
+ }
526
+ ```
527
+
528
+ ## Package Configuration
529
+
530
+ ### package.json
531
+
532
+ ```json
533
+ {
534
+ "name": "{service}-mcp-server",
535
+ "version": "1.0.0",
536
+ "description": "MCP server for {Service} API integration",
537
+ "type": "module",
538
+ "main": "dist/index.js",
539
+ "scripts": {
540
+ "start": "node dist/index.js",
541
+ "dev": "tsx watch src/index.ts",
542
+ "build": "tsc",
543
+ "clean": "rm -rf dist"
544
+ },
545
+ "engines": {
546
+ "node": ">=18"
547
+ },
548
+ "dependencies": {
549
+ "@modelcontextprotocol/sdk": "^1.6.1",
550
+ "axios": "^1.7.9",
551
+ "zod": "^3.23.8"
552
+ },
553
+ "devDependencies": {
554
+ "@types/node": "^22.10.0",
555
+ "tsx": "^4.19.2",
556
+ "typescript": "^5.7.2"
557
+ }
558
+ }
559
+ ```
560
+
561
+ ### tsconfig.json
562
+
563
+ ```json
564
+ {
565
+ "compilerOptions": {
566
+ "target": "ES2022",
567
+ "module": "Node16",
568
+ "moduleResolution": "Node16",
569
+ "lib": ["ES2022"],
570
+ "outDir": "./dist",
571
+ "rootDir": "./src",
572
+ "strict": true,
573
+ "esModuleInterop": true,
574
+ "skipLibCheck": true,
575
+ "forceConsistentCasingInFileNames": true,
576
+ "declaration": true,
577
+ "declarationMap": true,
578
+ "sourceMap": true,
579
+ "allowSyntheticDefaultImports": true
580
+ },
581
+ "include": ["src/**/*"],
582
+ "exclude": ["node_modules", "dist"]
583
+ }
584
+ ```
585
+
586
+ ## Complete Example
587
+
588
+ ```typescript
589
+ #!/usr/bin/env node
590
+ /**
591
+ * MCP Server for Example Service.
592
+ *
593
+ * This server provides tools to interact with Example API, including user search,
594
+ * project management, and data export capabilities.
595
+ */
596
+
597
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
598
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
599
+ import { z } from "zod";
600
+ import axios, { AxiosError } from "axios";
601
+
602
+ // Constants
603
+ const API_BASE_URL = "https://api.example.com/v1";
604
+ const CHARACTER_LIMIT = 25000;
605
+
606
+ // Enums
607
+ enum ResponseFormat {
608
+ MARKDOWN = "markdown",
609
+ JSON = "json"
610
+ }
611
+
612
+ // Zod schemas
613
+ const UserSearchInputSchema = z.object({
614
+ query: z.string()
615
+ .min(2, "Query must be at least 2 characters")
616
+ .max(200, "Query must not exceed 200 characters")
617
+ .describe("Search string to match against names/emails"),
618
+ limit: z.number()
619
+ .int()
620
+ .min(1)
621
+ .max(100)
622
+ .default(20)
623
+ .describe("Maximum results to return"),
624
+ offset: z.number()
625
+ .int()
626
+ .min(0)
627
+ .default(0)
628
+ .describe("Number of results to skip for pagination"),
629
+ response_format: z.nativeEnum(ResponseFormat)
630
+ .default(ResponseFormat.MARKDOWN)
631
+ .describe("Output format: 'markdown' for human-readable or 'json' for machine-readable")
632
+ }).strict();
633
+
634
+ type UserSearchInput = z.infer<typeof UserSearchInputSchema>;
635
+
636
+ // Shared utility functions
637
+ async function makeApiRequest<T>(
638
+ endpoint: string,
639
+ method: "GET" | "POST" | "PUT" | "DELETE" = "GET",
640
+ data?: any,
641
+ params?: any
642
+ ): Promise<T> {
643
+ try {
644
+ const response = await axios({
645
+ method,
646
+ url: `${API_BASE_URL}/${endpoint}`,
647
+ data,
648
+ params,
649
+ timeout: 30000,
650
+ headers: {
651
+ "Content-Type": "application/json",
652
+ "Accept": "application/json"
653
+ }
654
+ });
655
+ return response.data;
656
+ } catch (error) {
657
+ throw error;
658
+ }
659
+ }
660
+
661
+ function handleApiError(error: unknown): string {
662
+ if (error instanceof AxiosError) {
663
+ if (error.response) {
664
+ switch (error.response.status) {
665
+ case 404:
666
+ return "Error: Resource not found. Please check the ID is correct.";
667
+ case 403:
668
+ return "Error: Permission denied. You don't have access to this resource.";
669
+ case 429:
670
+ return "Error: Rate limit exceeded. Please wait before making more requests.";
671
+ default:
672
+ return `Error: API request failed with status ${error.response.status}`;
673
+ }
674
+ } else if (error.code === "ECONNABORTED") {
675
+ return "Error: Request timed out. Please try again.";
676
+ }
677
+ }
678
+ return `Error: Unexpected error occurred: ${error instanceof Error ? error.message : String(error)}`;
679
+ }
680
+
681
+ // Create MCP server instance
682
+ const server = new McpServer({
683
+ name: "example-mcp",
684
+ version: "1.0.0"
685
+ });
686
+
687
+ // Register tools
688
+ server.registerTool(
689
+ "example_search_users",
690
+ {
691
+ title: "Search Example Users",
692
+ description: `[Full description as shown above]`,
693
+ inputSchema: UserSearchInputSchema,
694
+ annotations: {
695
+ readOnlyHint: true,
696
+ destructiveHint: false,
697
+ idempotentHint: true,
698
+ openWorldHint: true
699
+ }
700
+ },
701
+ async (params: UserSearchInput) => {
702
+ // Implementation as shown above
703
+ }
704
+ );
705
+
706
+ // Main function
707
+ // For stdio (local):
708
+ async function runStdio() {
709
+ if (!process.env.EXAMPLE_API_KEY) {
710
+ console.error("ERROR: EXAMPLE_API_KEY environment variable is required");
711
+ process.exit(1);
712
+ }
713
+
714
+ const transport = new StdioServerTransport();
715
+ await server.connect(transport);
716
+ console.error("MCP server running via stdio");
717
+ }
718
+
719
+ // For streamable HTTP (remote):
720
+ async function runHTTP() {
721
+ if (!process.env.EXAMPLE_API_KEY) {
722
+ console.error("ERROR: EXAMPLE_API_KEY environment variable is required");
723
+ process.exit(1);
724
+ }
725
+
726
+ const app = express();
727
+ app.use(express.json());
728
+
729
+ app.post('/mcp', async (req, res) => {
730
+ const transport = new StreamableHTTPServerTransport({
731
+ sessionIdGenerator: undefined,
732
+ enableJsonResponse: true
733
+ });
734
+ res.on('close', () => transport.close());
735
+ await server.connect(transport);
736
+ await transport.handleRequest(req, res, req.body);
737
+ });
738
+
739
+ const port = parseInt(process.env.PORT || '3000');
740
+ app.listen(port, () => {
741
+ console.error(`MCP server running on http://localhost:${port}/mcp`);
742
+ });
743
+ }
744
+
745
+ // Choose transport based on environment
746
+ const transport = process.env.TRANSPORT || 'stdio';
747
+ if (transport === 'http') {
748
+ runHTTP().catch(error => {
749
+ console.error("Server error:", error);
750
+ process.exit(1);
751
+ });
752
+ } else {
753
+ runStdio().catch(error => {
754
+ console.error("Server error:", error);
755
+ process.exit(1);
756
+ });
757
+ }
758
+ ```
759
+
760
+ ---
761
+
762
+ ## Advanced MCP Features
763
+
764
+ ### Resource Registration
765
+
766
+ Expose data as resources for efficient, URI-based access:
767
+
768
+ ```typescript
769
+ import { ResourceTemplate } from "@modelcontextprotocol/sdk/types.js";
770
+
771
+ // Register a resource with URI template
772
+ server.registerResource(
773
+ {
774
+ uri: "file://documents/{name}",
775
+ name: "Document Resource",
776
+ description: "Access documents by name",
777
+ mimeType: "text/plain"
778
+ },
779
+ async (uri: string) => {
780
+ // Extract parameter from URI
781
+ const match = uri.match(/^file:\/\/documents\/(.+)$/);
782
+ if (!match) {
783
+ throw new Error("Invalid URI format");
784
+ }
785
+
786
+ const documentName = match[1];
787
+ const content = await loadDocument(documentName);
788
+
789
+ return {
790
+ contents: [{
791
+ uri,
792
+ mimeType: "text/plain",
793
+ text: content
794
+ }]
795
+ };
796
+ }
797
+ );
798
+
799
+ // List available resources dynamically
800
+ server.registerResourceList(async () => {
801
+ const documents = await getAvailableDocuments();
802
+ return {
803
+ resources: documents.map(doc => ({
804
+ uri: `file://documents/${doc.name}`,
805
+ name: doc.name,
806
+ mimeType: "text/plain",
807
+ description: doc.description
808
+ }))
809
+ };
810
+ });
811
+ ```
812
+
813
+ **When to use Resources vs Tools:**
814
+ - **Resources**: For data access with simple URI-based parameters
815
+ - **Tools**: For complex operations requiring validation and business logic
816
+ - **Resources**: When data is relatively static or template-based
817
+ - **Tools**: When operations have side effects or complex workflows
818
+
819
+ ### Transport Options
820
+
821
+ The TypeScript SDK supports two main transport mechanisms:
822
+
823
+ #### Streamable HTTP (Recommended for Remote Servers)
824
+
825
+ ```typescript
826
+ import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
827
+ import express from "express";
828
+
829
+ const app = express();
830
+ app.use(express.json());
831
+
832
+ app.post('/mcp', async (req, res) => {
833
+ // Create new transport for each request (stateless, prevents request ID collisions)
834
+ const transport = new StreamableHTTPServerTransport({
835
+ sessionIdGenerator: undefined,
836
+ enableJsonResponse: true
837
+ });
838
+
839
+ res.on('close', () => transport.close());
840
+
841
+ await server.connect(transport);
842
+ await transport.handleRequest(req, res, req.body);
843
+ });
844
+
845
+ app.listen(3000);
846
+ ```
847
+
848
+ #### stdio (For Local Integrations)
849
+
850
+ ```typescript
851
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
852
+
853
+ const transport = new StdioServerTransport();
854
+ await server.connect(transport);
855
+ ```
856
+
857
+ **Transport selection:**
858
+ - **Streamable HTTP**: Web services, remote access, multiple clients
859
+ - **stdio**: Command-line tools, local development, subprocess integration
860
+
861
+ ### Notification Support
862
+
863
+ Notify clients when server state changes:
864
+
865
+ ```typescript
866
+ // Notify when tools list changes
867
+ server.notification({
868
+ method: "notifications/tools/list_changed"
869
+ });
870
+
871
+ // Notify when resources change
872
+ server.notification({
873
+ method: "notifications/resources/list_changed"
874
+ });
875
+ ```
876
+
877
+ Use notifications sparingly - only when server capabilities genuinely change.
878
+
879
+ ---
880
+
881
+ ## Code Best Practices
882
+
883
+ ### Code Composability and Reusability
884
+
885
+ Your implementation MUST prioritize composability and code reuse:
886
+
887
+ 1. **Extract Common Functionality**:
888
+ - Create reusable helper functions for operations used across multiple tools
889
+ - Build shared API clients for HTTP requests instead of duplicating code
890
+ - Centralize error handling logic in utility functions
891
+ - Extract business logic into dedicated functions that can be composed
892
+ - Extract shared markdown or JSON field selection & formatting functionality
893
+
894
+ 2. **Avoid Duplication**:
895
+ - NEVER copy-paste similar code between tools
896
+ - If you find yourself writing similar logic twice, extract it into a function
897
+ - Common operations like pagination, filtering, field selection, and formatting should be shared
898
+ - Authentication/authorization logic should be centralized
899
+
900
+ ## Building and Running
901
+
902
+ Always build your TypeScript code before running:
903
+
904
+ ```bash
905
+ # Build the project
906
+ npm run build
907
+
908
+ # Run the server
909
+ npm start
910
+
911
+ # Development with auto-reload
912
+ npm run dev
913
+ ```
914
+
915
+ Always ensure `npm run build` completes successfully before considering the implementation complete.
916
+
917
+ ## Quality Checklist
918
+
919
+ Before finalizing your Node/TypeScript MCP server implementation, ensure:
920
+
921
+ ### Strategic Design
922
+ - [ ] Tools enable complete workflows, not just API endpoint wrappers
923
+ - [ ] Tool names reflect natural task subdivisions
924
+ - [ ] Response formats optimize for agent context efficiency
925
+ - [ ] Human-readable identifiers used where appropriate
926
+ - [ ] Error messages guide agents toward correct usage
927
+
928
+ ### Implementation Quality
929
+ - [ ] FOCUSED IMPLEMENTATION: Most important and valuable tools implemented
930
+ - [ ] All tools registered using `registerTool` with complete configuration
931
+ - [ ] All tools include `title`, `description`, `inputSchema`, and `annotations`
932
+ - [ ] Annotations correctly set (readOnlyHint, destructiveHint, idempotentHint, openWorldHint)
933
+ - [ ] All tools use Zod schemas for runtime input validation with `.strict()` enforcement
934
+ - [ ] All Zod schemas have proper constraints and descriptive error messages
935
+ - [ ] All tools have comprehensive descriptions with explicit input/output types
936
+ - [ ] Descriptions include return value examples and complete schema documentation
937
+ - [ ] Error messages are clear, actionable, and educational
938
+
939
+ ### TypeScript Quality
940
+ - [ ] TypeScript interfaces are defined for all data structures
941
+ - [ ] Strict TypeScript is enabled in tsconfig.json
942
+ - [ ] No use of `any` type - use `unknown` or proper types instead
943
+ - [ ] All async functions have explicit Promise<T> return types
944
+ - [ ] Error handling uses proper type guards (e.g., `axios.isAxiosError`, `z.ZodError`)
945
+
946
+ ### Advanced Features (where applicable)
947
+ - [ ] Resources registered for appropriate data endpoints
948
+ - [ ] Appropriate transport configured (stdio or streamable HTTP)
949
+ - [ ] Notifications implemented for dynamic server capabilities
950
+ - [ ] Type-safe with SDK interfaces
951
+
952
+ ### Project Configuration
953
+ - [ ] Package.json includes all necessary dependencies
954
+ - [ ] Build script produces working JavaScript in dist/ directory
955
+ - [ ] Main entry point is properly configured as dist/index.js
956
+ - [ ] Server name follows format: `{service}-mcp-server`
957
+ - [ ] tsconfig.json properly configured with strict mode
958
+
959
+ ### Code Quality
960
+ - [ ] Pagination is properly implemented where applicable
961
+ - [ ] Large responses check CHARACTER_LIMIT constant and truncate with clear messages
962
+ - [ ] Filtering options are provided for potentially large result sets
963
+ - [ ] All network operations handle timeouts and connection errors gracefully
964
+ - [ ] Common functionality is extracted into reusable functions
965
+ - [ ] Return types are consistent across similar operations
966
+
967
+ ### Testing and Build
968
+ - [ ] `npm run build` completes successfully without errors
969
+ - [ ] dist/index.js created and executable
970
+ - [ ] Server runs: `node dist/index.js --help`
971
+ - [ ] All imports resolve correctly
972
+ - [ ] Sample tool calls work as expected