### Install MCP SDK and Zod Source: https://github.com/cyanheads/model-context-protocol-resources/blob/main/guides/mcp-server-development-guide.md Install the necessary SDK and Zod for data validation. Always check for the latest stable versions before installing. ```bash # Check for the latest stable versions before installing npm install @modelcontextprotocol/sdk zod npm install -D typescript @types/node ``` -------------------------------- ### Setup MCP Client and LLM Integration Source: https://github.com/cyanheads/model-context-protocol-resources/blob/main/guides/mcp-client-development-guide.md Initializes an MCP client and a hypothetical LLM client. This setup is a prerequisite for interacting with LLM services through MCP. ```typescript import { Client } from '@modelcontextprotocol/sdk/client/index.js'; // Import your LLM client library // import { AnthropicClient } from '@anthropic-ai/sdk'; // Hypothetical LLM client class (you'll replace this with your actual LLM client) class LLMClient { async sendMessage(messages, options = {}) { // Implementation depends on your LLM provider console.log('Sending to LLM:', { messages, options }); return { id: 'msg_123', role: 'assistant', content: 'This is a sample response from the LLM.', tool_calls: [] // Will contain tool call requests if any }; } } async function setupLLMWithMCP() { // Set up MCP client const mcpClient = new Client( { name: 'ExampleClient', version: '1.0.0' }, { capabilities: { tools: {}, resources: {}, prompts: {} } } ); // Connect to MCP server const transport = new StdioClientTransport({ command: './server.js', args: [] }); await mcpClient.connect(transport); await mcpClient.initialize(); // Set up LLM client const llmClient = new LLMClient(); return { mcpClient, llmClient }; } ``` -------------------------------- ### MCP Client: Connect, Discover, and Call Capabilities Source: https://context7.com/cyanheads/model-context-protocol-resources/llms.txt Use the MCP TypeScript SDK `Client` class to connect to MCP servers, discover capabilities (tools, resources, prompts), and invoke them programmatically. This example demonstrates connecting via stdio, listing tools, calling a tool, reading a resource, and getting a prompt. ```typescript import { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"; async function main() { const client = new Client( { name: "ExampleClient", version: "1.0.0" }, { capabilities: { tools: {}, resources: {}, prompts: {} } } ); const transport = new StdioClientTransport({ command: "node", args: ["./build/index.js"], // Path to your MCP server }); await client.connect(transport); await client.initialize(); // Discover capabilities const { tools } = await client.listTools(); const { resources } = await client.listResources(); const { prompts } = await client.listPrompts(); console.log("Tools:", tools.map(t => t.name)); // Call a tool const toolResult = await client.callTool("calculate-bmi", { weightKg: 70, heightM: 1.75 }); if (toolResult.isError) { console.error("Tool error:", toolResult.content[0].text); } else { console.log("Result:", toolResult.content[0].text); // "BMI: 22.86" } // Read a resource const resource = await client.readResource("config://app"); console.log("Config:", resource.contents[0].text); // Get a prompt const prompt = await client.getPrompt("review-code", { code: "function hello() { return 'world'; }" }); console.log("Prompt messages:", prompt.messages); await client.close(); } main().catch(console.error); ``` -------------------------------- ### Local Server Setup with Stdio Transport Source: https://context7.com/cyanheads/model-context-protocol-resources/llms.txt Connects the MCP server to standard input/output, suitable for local tools launched as child processes. This example demonstrates a full echo server with resource, tool, and prompt capabilities. ```typescript import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; import { z } from "zod"; import { Role } from "@modelcontextprotocol/sdk/types.js"; import { ResourceTemplate } from "@modelcontextprotocol/sdk/server/mcp.js"; // Full minimal echo server demonstrating all three capability types async function startEchoServer() { const server = new McpServer({ name: "EchoServer", version: "1.0.0" }); server.resource( "echo-resource", new ResourceTemplate("echo://{message}", { list: undefined }), async (uri, { message }) => ({ contents: [{ uri: uri.href, mimeType: "text/plain", text: `Resource echo: ${message}` }], }) ); server.tool( "echo-tool", "Echoes back the provided message.", { message: z.string().min(1).describe("Message to echo") }, { title: "Echo Tool", readOnlyHint: true }, async ({ message }) => ({ content: [{ type: "text", text: `Tool echo: ${message}` }], }) ); server.prompt( "echo-prompt", "Creates a prompt containing the message.", { message: z.string().min(1).describe("Message for the prompt") }, ({ message }) => ({ messages: [{ role: Role.USER, content: [{ type: "text", text: `Please process this message: ${message}` }], }], }) ); const transport = new StdioServerTransport(); transport.onclose = () => { console.error("Transport closed."); process.exit(0); }; await server.connect(transport); console.error("EchoServer running via stdio."); } startEchoServer().catch(err => { console.error(err); process.exit(1); }); ``` -------------------------------- ### Start Echo Server with Resources, Tools, and Prompts (TypeScript) Source: https://github.com/cyanheads/model-context-protocol-resources/blob/main/guides/cyanheads-custom-mcp-llms-full.md Demonstrates how to set up an MCP server that handles echo resources, tools, and prompts. Ensure the logger utility is correctly configured. ```typescript import { McpServer, ResourceTemplate, } from "@modelcontextprotocol/sdk/server/mcp.js"; import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; import { z } from "zod"; import { Role } from "@modelcontextprotocol/sdk/types.js"; import { logger } from "../utils/logger.js"; // Assuming a logger utility async function startEchoServer() { const server = new McpServer({ name: "EchoServer", version: "1.0.0" }); // Echo Resource server.resource( "echo-resource", // Registration name new ResourceTemplate("echo://{message}", { list: undefined }), // URI Template async (uri, { message }) => { // Handler logger.debug(`Echo resource called: ${uri.href}`); return { contents: [ { uri: uri.href, mimeType: "text/plain", text: `Resource echo: ${message}`, }, ], }; } ); // Echo Tool server.tool( "echo-tool", // Tool name "Echoes back the provided message via a tool.", // Description { message: z.string().min(1).describe("Message to echo") }, // Input schema // Annotations: Title, read-only { title: "Echo Message (Tool)", readOnlyHint: true }, async ({ message }) => { // Handler logger.debug(`Echo tool called with message: ${message}`); return { content: [{ type: "text", text: `Tool echo: ${message}` }] }; } ); // Echo Prompt server.prompt( "echo-prompt", // Prompt name "Generates a prompt containing the message.", // Description { message: z.string().min(1).describe("Message for the prompt") }, // Argument schema ({ message }) => { // Handler logger.debug(`Echo prompt generated for message: ${message}`); return { messages: [ { role: Role.USER, content: [ { type: "text", text: `Please process this message: ${message}` }, ], }, ], }; } ); logger.info("Echo server configured."); const transport = new StdioServerTransport(); transport.onclose = () => { logger.info("Echo server transport closed."); process.exit(0); }; await server.connect(transport); logger.info("Echo server connected via Stdio."); } startEchoServer(); ``` -------------------------------- ### Start MCP Server with SQLite Integration Source: https://github.com/cyanheads/model-context-protocol-resources/blob/main/guides/mcp-server-development-guide.md Starts an MCP server, initializes the SQLite database, and registers a schema resource and a read-only SQL query tool. ```typescript async function startSQLiteServer() { try { await initializeDatabase(DB_PATH); logger.info(`Database ${DB_PATH} initialized/verified.`); } catch (error) { logger.error(`Failed to initialize database ${DB_PATH}:`, error); process.exit(1); // Exit if DB setup fails } const server = new McpServer ( { name: "SQLite Explorer", version: "1.0.0" }, { capabilities: { resources: { listChanged: false }, // Schema doesn't change dynamically tools: { listChanged: false }, }, } ); // Helper to open DB connection (read-only recommended for safety) const getDb = async (): Promise => { return open ({ filename: DB_PATH, driver: sqlite3.Database, mode: sqlite3.OPEN_READONLY, // Open in read-only mode for safety }); }; // Resource: Database Schema server.resource ( "db-schema", // Resource group name "db://schema", // Static URI for the schema async (uri) => { logger.debug(`Reading schema resource: ${uri.href}`); let db: Database | null = null; try { db = await getDb(); const tables = await db.all<{ name: string; sql: string }> ( "SELECT name, sql FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%';" ); const schemaText = tables .map((t) => `-- Table: ${t.name}\n${t.sql};`) .join("\n\n"); return { contents: [ { uri: uri.href, mimeType: "application/sql", // More specific MIME type text: schemaText || "-- No tables found --", }, ], }; } catch (error: any) { logger.error(`Schema retrieval error: ${error.message}`); throw new Error(`Failed to retrieve schema: ${error.message}`); } finally { await db?.close(); } } ); logger.info("Registered resource: db://schema"); // Tool: Execute Read-Only SQL Query const querySchema = z.object ({ sql: z .string() .trim() .min(1) .refine((s) => s.toLowerCase().startsWith("select"), { message: "Only SELECT queries are allowed.", // Zod refinement for basic check }) .describe("The read-only SQL SELECT query to execute"), }); server.tool ( "sqlQuery", // Tool name "Executes a read-only SQL SELECT query against the database.", // Description querySchema, // Input schema with refinement { readOnlyHint: true, title: "Run SQL Query" }, // Annotations async ({ sql }) => { logger.debug(`Executing query tool: ${sql}`); // Additional check (belt-and-suspenders) - Zod refine should catch this if (!/^\s*SELECT/i.test(sql)) { logger.warn(`Query tool rejected non-SELECT statement: ${sql}`); return { content: [ { type: "text", text: "Error: Only SELECT queries are allowed." }, ], isError: true, ``` -------------------------------- ### Start SQLite MCP Server Source: https://github.com/cyanheads/model-context-protocol-resources/blob/main/guides/cyanheads-custom-mcp-llms-full.md Initializes the SQLite database, creates a table if it doesn't exist, and sets up the MCP server with schema resource and query tool. Connects the server via Stdio transport. ```typescript import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; import sqlite3 from "sqlite3"; import { open } from "sqlite"; // Use the promise-based wrapper import { z } from "zod"; import { logger } from "../utils/logger.js"; // Assuming a logger utility const DB_FILE = "database.db"; // Ensure this file exists or is created async function startSQLiteServer() { // Initialize DB (Create table if not exists - example) const db = await open({ filename: DB_FILE, driver: sqlite3.Database }); await db.exec( "CREATE TABLE IF NOT EXISTS items (id INTEGER PRIMARY KEY, name TEXT)" ); await db.close(); logger.info(`Database ${DB_FILE} initialized.`); const server = new McpServer({ name: "SQLite Explorer", version: "1.0.0" }); // Resource to get table schema server.resource( "schema", "db://schema", // Simple URI for the schema async (uri) => { logger.debug(`Reading schema resource: ${uri.href}`); const db = await open({ filename: DB_FILE, driver: sqlite3.Database }); try { const tables = await db.all( "SELECT sql FROM sqlite_master WHERE type='table'" ); const schemaText = tables .map((t: { sql: string }) => t.sql) .join("\n\n"); return { contents: [ { uri: uri.href, mimeType: "text/sql", text: schemaText || "-- No tables found --", }, ], }; } finally { await db.close(); } } ); // Tool to execute a query server.tool( "query", "Executes a read-only SQL query.", { sql: z.string().min(1).describe("The SQL query to execute") }, { readOnlyHint: true, title: "Run SQL Query" }, // Annotations async ({ sql }) => { logger.debug(`Executing query tool: ${sql}`); // WARNING: The basic regex check below is INSUFFICIENT for production security // if the SQL query could potentially be influenced by untrusted input. // It only prevents the most basic modification attempts. For robust protection // against SQL injection, use parameterized queries or a dedicated query builder // that properly sanitizes inputs, especially if 'sql' originates from or is // influenced by external sources. Since this example assumes 'sql' comes // directly from the LLM/client (which should ideally be validated upstream), // this basic check is illustrative but not exhaustive. if (!/^\s*SELECT/i.test(sql)) { logger.warn(`Query tool rejected non-SELECT statement: ${sql}`); return { content: [ { type: "text", text: "Error: Only SELECT queries are allowed." }, ], isError: true, }; } const db = await open({ filename: DB_FILE, driver: sqlite3.Database }); try { const results = await db.all(sql); return { content: [{ type: "text", text: JSON.stringify(results, null, 2) }], }; } catch (err: unknown) { const error = err as Error; logger.error(`Query tool error: ${error.message}`, { sql }); return { content: [{ type: "text", text: `Error: ${error.message}` }], isError: true, }; } finally { await db.close(); } } ); logger.info("SQLite server configured."); const transport = new StdioServerTransport(); transport.onclose = () => { logger.info("SQLite server transport closed."); process.exit(0); }; await server.connect(transport); logger.info("SQLite server connected via Stdio."); } startSQLiteServer(); ``` -------------------------------- ### Stdio Transport - Local Server Setup Source: https://context7.com/cyanheads/model-context-protocol-resources/llms.txt Sets up a local server using the Stdio transport, which connects the server to standard input/output. This is useful for tools launched as child processes by a client. ```APIDOC ## Stdio Transport — Local Server Setup Connects the server to standard input/output, the simplest transport for local tools launched as child processes by the client (e.g., Claude Desktop). ### Example Server Setup ```typescript import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; import { z } from "zod"; import { Role } from "@modelcontextprotocol/sdk/types.js"; import { ResourceTemplate } from "@modelcontextprotocol/sdk/server/mcp.js"; // Full minimal echo server demonstrating all three capability types async function startEchoServer() { const server = new McpServer({ name: "EchoServer", version: "1.0.0" }); server.resource( "echo-resource", new ResourceTemplate("echo://{message}", { list: undefined }), async (uri, { message }) => ({ contents: [{ uri: uri.href, mimeType: "text/plain", text: `Resource echo: ${message}` }], }) ); server.tool( "echo-tool", "Echoes back the provided message.", { message: z.string().min(1).describe("Message to echo") }, { title: "Echo Tool", readOnlyHint: true }, async ({ message }) => ({ content: [{ type: "text", text: `Tool echo: ${message}` }], }) ); server.prompt( "echo-prompt", "Creates a prompt containing the message.", { message: z.string().min(1).describe("Message for the prompt") }, ({ message }) => ({ messages: [{ role: Role.USER, content: [{ type: "text", text: `Please process this message: ${message}` }], }], }) ); const transport = new StdioServerTransport(); transport.onclose = () => { console.error("Transport closed."); process.exit(0); }; await server.connect(transport); console.error("EchoServer running via stdio."); } startEchoServer().catch(err => { console.error(err); process.exit(1); }); ``` ``` -------------------------------- ### Start Stdio Server with MCP Source: https://github.com/cyanheads/model-context-protocol-resources/blob/main/guides/cyanheads-custom-mcp-llms-full.md Use this snippet to initialize an MCP server with the Stdio transport for local command-line applications. Ensure necessary imports and logger utilities are available. ```typescript import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; import { logger } from "../utils/logger.js"; // Assuming a logger utility async function startStdioServer() { const server = new McpServer({ name: "stdio-server", version: "1.0.0" }); // ... register resources, tools, prompts using server.resource(), server.tool(), server.prompt() ... logger.info("Stdio Server configured."); const transport = new StdioServerTransport(); transport.onclose = () => { logger.info("Stdio transport closed. Exiting."); process.exit(0); }; await server.connect(transport); logger.info("Server connected via Stdio."); } startStdioServer(); ``` -------------------------------- ### Dynamic Server Tool Management Example Source: https://github.com/cyanheads/model-context-protocol-resources/blob/main/guides/mcp-server-development-guide.md Demonstrates dynamic management of server tools, including enabling, disabling, updating schemas, and removing tools based on authorization changes. Use this to modify server capabilities post-connection. ```typescript import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; import { z } from "zod"; import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; import { logger } from "../utils/logger.js"; // Assuming a logger utility // Assume listMessages, putMessage, upgradeAuthAndStoreToken functions exist const server = new McpServer({ name: "Dynamic Example", version: "1.0.0", }); // Register initial tools const listMessageTool = server.tool( "listMessages", "Lists messages in a channel.", { channel: z.string().describe("Channel name") }, // Annotations: Title, read-only { title: "List Channel Messages", readOnlyHint: true }, async ({ channel }) => ({ content: [{ type: "text", text: await listMessages(channel) }], }) ); const putMessageTool = server.tool( "putMessage", "Sends a message to a channel.", { channel: z.string().describe("Channel name"), message: z.string().min(1).describe("Message content"), }, // Annotations: Title (not read-only, potentially idempotent depending on backend) { title: "Send Channel Message" /* idempotentHint: true (optional) */ }, async ({ channel, message }) => ({ content: [{ type: "text", text: await putMessage(channel, message) }], }) ); // Start with the 'putMessage' tool disabled putMessageTool.disable(); logger.info(`Tool 'putMessage' initially disabled.`); const upgradeAuthTool = server.tool( "upgradeAuth", "Upgrades authorization level.", { permission: z .enum(["write", "admin"]) .describe("Permission level to upgrade to"), }, // Annotations: Title (modifies state, not read-only) { title: "Upgrade Authorization" /* destructiveHint: false (usually not destructive) */, }, // Handler receives validated arguments async ({ permission }) => { logger.info(`Attempting to upgrade auth to: ${permission}`); // Assume this function handles the auth logic and returns status const { ok, err, previousPermission } = await upgradeAuthAndStoreToken( permission ); if (!ok) { logger.error(`Auth upgrade failed: ${err}`); return { content: [{ type: "text", text: `Error: ${err}` }], isError: true, }; } logger.info( `Auth upgraded successfully from ${previousPermission} to ${permission}.` ); // If we previously had read-only access (or similar), enable 'putMessage' if (previousPermission !== "write" && previousPermission !== "admin") { logger.info(`Enabling 'putMessage' tool.`); putMessageTool.enable(); // Automatically sends listChanged } if (permission === "write") { // If upgraded to 'write', update 'upgradeAuth' to only allow 'admin' next logger.info(`Updating 'upgradeAuth' tool to only allow 'admin' upgrade.`); upgradeAuthTool.update({ // Only update the schema part paramSchema: { permission: z.enum(["admin"]).describe("Upgrade to admin permission"), }, }); // Automatically sends listChanged } else if (permission === "admin") { // If upgraded to 'admin', remove the upgrade tool entirely logger.info(`Removing 'upgradeAuth' tool as user is now admin.`); upgradeAuthTool.remove(); // Automatically sends listChanged } return { content: [ { type: "text", text: `Successfully upgraded auth to ${permission}` }, ], }; } ); // Connect the server (example using Stdio) async function startServer() { logger.info("Starting dynamic server example..."); const transport = new StdioServerTransport(); transport.onclose = () => { logger.info("Transport closed."); process.exit(0); }; await server.connect(transport); logger.info("Server connected via Stdio."); } startServer(); // --- Dummy implementations for demonstration --- async function listMessages(channel: string): Promise { return `Messages in ${channel}`; } async function putMessage(channel: string, message: string): Promise { return `Message "${message}" sent to ${channel}`; } async function upgradeAuthAndStoreToken( permission: "write" | "admin" ): Promise<{ ok: boolean; err?: string; previousPermission: string }> { // Simulate auth upgrade logic // In a real app, interact with auth system and store token const currentPermission = permission === "write" ? "read" : "write"; // Simulate previous state return { ok: true, previousPermission: currentPermission }; } ``` -------------------------------- ### Conceptual MCP Server Setup with Express (HTTP Transport) Source: https://github.com/cyanheads/model-context-protocol-resources/blob/main/guides/mcp-server-development-guide.md Illustrates a conceptual setup for an MCP server using Express for HTTP transport. This approach is suitable for servers running as independent processes, potentially handling multiple clients. Consult SDK documentation for specific transport implementations. ```typescript import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; // The MCP SDK provides transport implementations that integrate with frameworks // like Express or can be used with Node's built-in http module. Consult the // specific SDK documentation for available transport classes and integration helpers. // This example shows a conceptual integration with Express. import express, { Request, Response } from "express"; async function startServer() { ``` -------------------------------- ### Install Dependencies for MCP Project (Bash) Source: https://context7.com/cyanheads/model-context-protocol-resources/llms.txt Installs necessary dependencies and sets up a new TypeScript MCP project. Includes SDK, Zod, TypeScript, and Node types. ```bash mkdir my-mcp-server && cd my-mcp-server npm init -y npm install @modelcontextprotocol/sdk zod npm install -D typescript @types/node mkdir src && touch src/index.ts ``` -------------------------------- ### Manual Testing with stdio Source: https://context7.com/cyanheads/model-context-protocol-resources/llms.txt Examples of sending JSON-RPC 2.0 messages via standard input for manual testing of MCP processes. These commands demonstrate how to invoke different methods like 'tools/list', 'resources/read', and 'prompts/get'. ```bash // Send via stdio for manual testing: // echo '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}' | node build/index.js ``` ```bash // echo '{"jsonrpc":"2.0","id":2,"method":"resources/read","params":{"uri":"config://app"}}' | node build/index.js ``` ```bash // echo '{"jsonrpc":"2.0","id":3,"method":"prompts/get","params":{"name":"review-code","arguments":{"code":"const x=1"}}}' | node build/index.js ``` -------------------------------- ### Implement Core MCP Server Interface Source: https://github.com/cyanheads/model-context-protocol-resources/blob/main/guides/mcp-server-development-guide.md This TypeScript code demonstrates how to set up a basic MCP server, define a 'greet' tool with Zod validation for input, and connect it to a stdio transport. It logs server status and errors to stderr. Ensure zod is installed (`npm install zod`). ```typescript #!/usr/bin/env node import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; import { z } from "zod"; // Import zod for schema validation async function main() { // 1. Create an MCP server instance const server = new McpServer( { // Server identification name: "GreetingServer", version: "1.0.1", }, { // Declare server capabilities capabilities: { tools: { listChanged: false }, // We support tools, no dynamic changes // resources: {}, // Uncomment if supporting resources // prompts: {}, // Uncomment if supporting prompts }, } ); // 2. Define the input schema for the 'greet' tool using zod const greetInputSchema = z.object({ name: z.string().min(1).describe("The name of the person to greet"), }); // 3. Add the 'greet' tool implementation server.tool( "greet", // Tool name greetInputSchema, // Use the zod schema for input validation async (input) => { // Input is automatically validated against the schema const message = `Hello, ${input.name}! Welcome to MCP.`; console.error(`Tool 'greet' called with name: ${input.name}`); // Log to stderr // Return the result conforming to CallToolResultContent return { content: [{ type: "text", text: message }], // isError: false, // Default is false }; } ); // 4. Create a transport (stdio for this example) const transport = new StdioServerTransport(); // 5. Connect the server to the transport and start listening try { await server.connect(transport); console.error("Greeting MCP Server is running and connected via stdio."); // Log to stderr } catch (error) { console.error("Failed to connect server:", error); process.exit(1); } // Keep the server running (for stdio, it runs until stdin closes) // For other transports like HTTP, you'd typically have a server.listen() call } // Run the main function main().catch((error) => { console.error("Unhandled error during server startup:", error); process.exit(1); }); ``` -------------------------------- ### Modular Tool Structure for MCP Server Source: https://github.com/cyanheads/model-context-protocol-resources/blob/main/guides/cyanheads-custom-mcp-llms-full.md Organize tool logic and registration into separate files for better maintainability. This example shows a tool's logic, input schema, and registration separated into different modules. ```typescript // --- src/mcp-server/tools/myTool/myToolLogic.ts --- // Contains the core logic and schema for the tool. import { z } from "zod"; import { TextContent } from "@modelcontextprotocol/sdk/types.js"; import { logger } from "../../../utils/logger.js"; // Adjust path as needed // Define input schema using Zod export const myToolInputSchema = z.object({ parameter1: z.string().describe("Description for parameter 1"), parameter2: z.number().optional().describe("Optional number parameter"), }); // Define the handler function export async function handleMyTool( args: z.infer ): Promise<{ content: TextContent[]; isError?: boolean }> { logger.debug("Executing myTool logic", args); // --- Tool implementation goes here --- const resultText = `Processed ${args.parameter1} with optional ${args.parameter2 ?? "N/A"}`; return { content: [{ type: "text", text: resultText }], }; } ``` ```typescript // --- src/mcp-server/tools/myTool/registration.ts --- // Handles registering the tool with the McpServer instance. import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; import { myToolInputSchema, handleMyTool } from "./myToolLogic.js"; import { logger } from "../../../utils/logger.js"; // Adjust path as needed export function registerMyTool(server: McpServer): void { server.tool( "my-tool", // Tool name "A description of what my-tool does.", // Description myToolInputSchema, // Pass the imported schema shape // Optional annotations { title: "My Awesome Tool", readOnlyHint: true }, handleMyTool // Pass the imported handler function ); logger.info("Registered tool: my-tool"); } ``` ```typescript // --- src/mcp-server/server.ts --- // The main server orchestration file imports and calls registration functions. import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; import { registerMyTool } from "./tools/myTool/registration.js"; // Import registration import { config } from "../../config/index.js"; // Adjust path as needed import { logger } from "../../utils/logger.js"; // Adjust path as needed // ... other imports like transports ... function createMcpServerInstance(): McpServer { const server = new McpServer( { name: config.mcpServerName, version: config.mcpServerVersion }, { /* capabilities */ } ); // Register capabilities by calling their registration functions registerMyTool(server); // registerOtherTool(server); // registerMyResource(server); logger.info("MCP Server instance configured with capabilities."); return server; } // ... rest of server startup logic (transports, etc.) ... ``` -------------------------------- ### SQLite Explorer MCP Server Example Source: https://context7.com/cyanheads/model-context-protocol-resources/llms.txt A complete MCP server integrating with a SQLite database. It exposes the database schema as a resource and provides a tool for executing safe SELECT queries. Ensure SQLite3 and Zod are installed. ```typescript import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; import sqlite3 from "sqlite3"; import { open } from "sqlite"; import { z } from "zod"; const DB_PATH = "./database.db"; async function startSQLiteServer() { // Initialize DB schema const db = await open({ filename: DB_PATH, driver: sqlite3.Database }); await db.exec(` CREATE TABLE IF NOT EXISTS items (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, value REAL); INSERT OR IGNORE INTO items (id, name, value) VALUES (1, 'Sample', 42.0); `); await db.close(); const server = new McpServer({ name: "SQLite Explorer", version: "1.0.0" }); // Resource: expose schema as readable data server.resource("db-schema", "db://schema", async (uri) => { const db = await open({ filename: DB_PATH, driver: sqlite3.Database, mode: sqlite3.OPEN_READONLY }); try { const tables = await db.all<{ name: string; sql: string }[]>( "SELECT name, sql FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'" ); return { contents: [{ uri: uri.href, mimeType: "application/sql", text: tables.map(t => `-- ${t.name}\n${t.sql};`).join("\n\n") || "-- No tables --", }], }; } finally { await db.close(); } }); // Tool: safe read-only query execution server.tool( "sqlQuery", "Executes a read-only SQL SELECT query.", { sql: z.string().trim().min(1) .refine(s => /^\s*SELECT/i.test(s), { message: "Only SELECT queries allowed" }) .describe("SQL SELECT query to execute"), }, { readOnlyHint: true, title: "Run SQL Query" }, async ({ sql }) => { const db = await open({ filename: DB_PATH, driver: sqlite3.Database, mode: sqlite3.OPEN_READONLY }); try { const results = await Promise.race([ db.all(sql), new Promise((_, rej) => setTimeout(() => rej(new Error("Query timeout")), 5000)), ]); const MAX = 50; const text = JSON.stringify((results as unknown[]).slice(0, MAX), null, 2) + ((results as unknown[]).length > MAX ? `\n\n...(truncated, ${(results as unknown[]).length} rows total)` : ""); return { content: [{ type: "text", text }] }; } catch (err) { return { content: [{ type: "text", text: `Error: ${(err as Error).message}` }], isError: true }; } finally { await db.close(); } } ); const transport = new StdioServerTransport(); transport.onclose = () => process.exit(0); await server.connect(transport); console.error("SQLite Explorer running."); } startSQLiteServer().catch(err => { console.error(err); process.exit(1); }); ``` -------------------------------- ### Execute Tool with Multi-Server Client Manager Source: https://github.com/cyanheads/model-context-protocol-resources/blob/main/guides/mcp-client-development-guide.md Demonstrates executing a tool named 'add' with arguments and handling potential errors. Ensure the manager is properly initialized before use. ```javascript const result = await manager.executeTool('add', { a: 5, b: 3 }); console.log('Result:', result); } catch (error) { console.error('Error executing tool:', error); } // Clean up await manager.close(); } runMultiServerExample().catch(console.error); ``` -------------------------------- ### Stateless Streamable HTTP Transport Setup Source: https://github.com/cyanheads/model-context-protocol-resources/blob/main/guides/cyanheads-custom-mcp-llms-full.md Sets up a stateless HTTP server for MCP requests. A new server and transport are created for each incoming POST request to ensure isolation. GET and DELETE methods are explicitly disallowed. ```typescript import express, { Request, Response } from "express"; import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js"; import { logger } from "../utils/logger.js"; // Assuming a logger utility import { config } from "../config/index.js"; // Assuming a config module const HTTP_PORT = config.mcpHttpPort; // Load from config const HTTP_HOST = config.mcpHttpHost; // Load from config const MCP_ENDPOINT_PATH = "/mcp"; // Function to create and configure a server instance (must be stateless) function createStatelessServerInstance(): McpServer { const server = new McpServer({ name: "http-stateless-server", version: "1.0.0", }); // ... register ONLY stateless resources, tools, prompts ... logger.info("Created new STATELESS McpServer instance."); return server; } async function startStatelessHttpServer() { const app = express(); app.use(express.json()); // IMPORTANT: Add security middleware (CORS, Origin check, Auth) here! app.post(MCP_ENDPOINT_PATH, async (req: Request, res: Response) => { // Create a new server and transport for each request to ensure isolation let server: McpServer | null = null; let transport: StreamableHTTPServerTransport | null = null; try { server = createStatelessServerInstance(); transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined, }); // No sessions // Ensure cleanup happens when the client disconnects res.on("close", () => { logger.debug("Stateless request connection closed, cleaning up."); transport?.close(); // Close transport server?.close(); // Close server instance }); await server.connect(transport); await transport.handleRequest(req, res, req.body); } catch (error) { logger.error("Error handling stateless MCP POST request:", { error }); // Ensure cleanup even on error transport?.close(); server?.close(); if (!res.headersSent) { res.status(500).json({ jsonrpc: "2.0", error: { code: -32603, message: "Internal server error" }, id: null, }); } } }); // GET and DELETE are not typically supported in stateless mode without sessions const methodNotAllowedHandler = (req: Request, res: Response) => { logger.warn(`Method ${req.method} not allowed on stateless endpoint.`); res.status(405).json({ jsonrpc: "2.0", error: { code: -32000, message: "Method Not Allowed" }, id: null, }); }; app.get(MCP_ENDPOINT_PATH, methodNotAllowedHandler); app.delete(MCP_ENDPOINT_PATH, methodNotAllowedHandler); // Use HTTP_HOST from config for binding app.listen(HTTP_PORT, HTTP_HOST, () => { logger.info( `Stateless Streamable HTTP Server listening on ${HTTP_HOST}:${HTTP_PORT}` ); }); } startStatelessHttpServer(); ``` -------------------------------- ### Initialize Node.js Project Source: https://github.com/cyanheads/model-context-protocol-resources/blob/main/guides/mcp-client-development-guide.md Command to initialize a new Node.js project with a package.json file. ```bash npm init -y ``` -------------------------------- ### Install TypeScript and Zod Source: https://github.com/cyanheads/model-context-protocol-resources/blob/main/guides/mcp-client-development-guide.md Command to install TypeScript for type checking and Zod for schema validation. ```bash npm install typescript zod ``` -------------------------------- ### Install MCP TypeScript SDK Source: https://github.com/cyanheads/model-context-protocol-resources/blob/main/guides/mcp-client-development-guide.md Command to install the official MCP TypeScript SDK using npm. ```bash npm install @modelcontextprotocol/sdk ``` -------------------------------- ### MCP Notification Example Source: https://github.com/cyanheads/model-context-protocol-resources/blob/main/guides/mcp-server-development-guide.md An example of a JSON-RPC 2.0 notification message. Notifications do not have an 'id' and are one-way messages. ```typescript { "jsonrpc": "2.0", "method": "notifications/tools/list_changed" } ``` -------------------------------- ### Initialize and Configure MCP Server Source: https://github.com/cyanheads/model-context-protocol-resources/blob/main/guides/mcp-server-development-guide.md Sets up the MCP server, ensures a data directory exists, and registers a static resource for application configuration. ```typescript import { McpServer, ResourceTemplate, } from "@modelcontextprotocol/sdk/server/mcp.js"; import { McpSchema } from "@modelcontextprotocol/sdk/types.js"; // Import base schema types import fs from "fs/promises"; import path from "path"; import { fileURLToPath } from "url"; // For ES Modules __dirname equivalent import { logger } from "../utils/logger.js"; // Assuming a logger utility // Assume 'server' is an initialized McpServer instance // Get directory relative to the current module file const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); const DATA_DIR = path.resolve(__dirname, "../data"); // Example: data dir sibling to src // Ensure data directory exists try { await fs.mkdir(DATA_DIR, { recursive: true }); logger.info(`Data directory ensured: ${DATA_DIR}`); } catch (error) { logger.error(`Failed to create data directory ${DATA_DIR}:`, error); // Decide if this is a fatal error for the server } // Static resource example server.resource( "app-config", // Unique name for this resource registration "config://app", // The URI clients will use async (uri) => { // Handler function logger.debug(`Reading resource: ${uri.href}`); // In a real app, load config from a file or environment const configData = { settingA: "valueA", settingB: 123 }; return { contents: [ { uri: uri.href, // Echo back the requested URI mimeType: "application/json", // Specify the content type text: JSON.stringify(configData, null, 2), // The actual content }, ], }; } ); logger.info(`Registered static resource: config://app`); ``` -------------------------------- ### MCP Error Response Example Source: https://github.com/cyanheads/model-context-protocol-resources/blob/main/guides/mcp-server-development-guide.md Shows an example of a JSON-RPC 2.0 error response, containing 'jsonrpc' version, the request 'id', and an 'error' object with code, message, and optional data. ```typescript { "jsonrpc": "2.0", "id": 123, "error": { "code": -32602, // JSON-RPC error code "message": "Invalid parameters", "data": { "details": "Missing required argument 'arg1'" } } } ``` -------------------------------- ### Initialize MCP Server (High-Level TypeScript SDK) Source: https://github.com/cyanheads/model-context-protocol-resources/blob/main/guides/cyanheads-custom-mcp-llms-full.md Instantiate an McpServer with server information, capabilities, and optional instructions. Explicitly declaring capabilities improves clarity and ensures protocol features are advertised correctly. Assumes logger and config utilities are available. ```typescript import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; import { logger } from "../utils/logger.js"; // Assuming a logger utility import { config } from "../config/index.js"; // Assuming a config module // Server Info and Capabilities are defined during McpServer instantiation const server = new McpServer( { // Server Information (Loaded from config) name: config.mcpServerName, version: config.mcpServerVersion, }, { // Server Capabilities Declaration // While the SDK can infer capabilities, explicitly declaring them improves clarity. capabilities: { logging: {}, // Example: Enable logging capability resources: { listChanged: true }, // Example: Support dynamic resource lists tools: { listChanged: true }, // Example: Support dynamic tool lists // prompts: { listChanged: true }, // Example: Support dynamic prompt lists }, // Optional instructions for the client/LLM instructions: `This server (${config.mcpServerName} v${config.mcpServerVersion}) uses the high-level SDK.`, } ); logger.info("High-level MCP Server instance created."); // Connection logic depends on the chosen transport (see Section 7) // Example for Stdio: // const transport = new StdioServerTransport(); // await server.connect(transport); // logger.info("Server connected via Stdio."); ``` -------------------------------- ### MCP Success Response Example Source: https://github.com/cyanheads/model-context-protocol-resources/blob/main/guides/mcp-server-development-guide.md Demonstrates a successful JSON-RPC 2.0 response, including the 'jsonrpc' version, the original request 'id', and the 'result' payload. ```typescript { "jsonrpc": "2.0", "id": 123, "result": { "output": "Success!" } } ```