### Install MCP Framework Globally Source: https://mcp-framework.com/docs/introduction/quickstart Installs the `mcp-framework` CLI tool globally using npm, allowing access to `mcp` commands from any directory. ```shell npm i -g mcp-framework ``` -------------------------------- ### Example Claude Desktop Prompt Source: https://mcp-framework.com/docs/introduction/quickstart An example natural language prompt to be used with the Claude Desktop client, demonstrating how to invoke the configured 'weather' tool. ```text Could you check the weather in London using the weather tool? ``` -------------------------------- ### Build and Start MCP Server Source: https://mcp-framework.com/docs/introduction/http-quickstart Provides the necessary commands to compile the TypeScript project using `npm run build` and then start the compiled MCP server using `npm start`. This makes the server accessible at the configured HTTP endpoint. ```bash # Build the project npm run build # Start the server npm start ``` -------------------------------- ### Install MCP Framework Globally Source: https://mcp-framework.com/docs/introduction/http-quickstart Installs the `mcp-framework` package globally using npm, making the `mcp` CLI command available system-wide. This is a prerequisite for using the MCP CLI tools. ```bash npm i -g mcp-framework ``` -------------------------------- ### Create Minimal MCP Framework Server Source: https://mcp-framework.com/docs/introduction/installation This TypeScript code snippet demonstrates how to create a basic MCP Framework server instance and start it, including error handling for server startup failures. ```TypeScript import { MCPServer } from "mcp-framework"; const server = new MCPServer(); server.start().catch((error) => { console.error("Server error:", error); process.exit(1); }); ``` -------------------------------- ### Create New MCP Project Source: https://mcp-framework.com/docs/introduction/quickstart Initializes a new MCP server project named 'weather-mcp-server' and navigates into its directory, setting up the basic project structure. ```shell mcp create weather-mcp-server cd weather-mcp-server ``` -------------------------------- ### Install MCP Framework CLI and Create New Project Source: https://mcp-framework.com/docs/introduction/installation This snippet demonstrates how to install the MCP Framework CLI globally using npm and then create a new project, navigate into it, and install its dependencies. ```Shell # Install the CLI globally with npm npm install -g mcp-framework # The mcp CLI is now globally available # Create your new project with the mcp CLI mcp create my-mcp-server # Navigate to your project cd my-mcp-server # Install dependencies npm install ``` -------------------------------- ### Start MCP Server Instance Source: https://mcp-framework.com/docs/introduction/server-configuration This snippet shows how to asynchronously start an `MCPServer` instance using the `start()` method. The start process involves loading tools, prompts, and resources, detecting capabilities, setting up request handlers, initializing the transport, and beginning to listen for client connections. ```typescript await server.start(); ``` -------------------------------- ### Build MCP Project Source: https://mcp-framework.com/docs/introduction/quickstart Compiles the MCP project, typically transpiling TypeScript to JavaScript and preparing it for execution. ```shell npm run build ``` -------------------------------- ### Launch MCP Experimental Debugger Source: https://mcp-framework.com/docs/introduction/http-quickstart Runs the `mcp-debug` tool via `npx` to help inspect and interact with the running MCP server. This tool facilitates sending requests and viewing responses for testing purposes. ```bash npx mcp-debug ``` -------------------------------- ### Example MCPServer Configuration with SSE and API Key Authentication Source: https://mcp-framework.com/docs/introduction/server-configuration This TypeScript code demonstrates a complete configuration for an MCPServer, including setting up an SSE transport with detailed options for endpoints, message size, CORS, and API key authentication. It also illustrates how to start the server and handle graceful shutdown using process signals. ```typescript import { MCPServer, APIKeyAuthProvider } from "@modelcontextprotocol/mcp-framework"; const server = new MCPServer({ name: "my-mcp-server", version: "1.0.0", basePath: "./dist", transport: { type: "sse", options: { port: 8080, endpoint: "/sse", messageEndpoint: "/messages", maxMessageSize: "4mb", headers: { "X-Custom-Header": "value" }, cors: { allowOrigin: "*", allowMethods: "GET, POST, OPTIONS", allowHeaders: "Content-Type, Authorization, x-api-key", exposeHeaders: "Content-Type, Authorization, x-api-key", maxAge: "86400" }, auth: { provider: new APIKeyAuthProvider({ keys: ["your-api-key"] }), endpoints: { sse: true, messages: true } } } } }); // Start the server await server.start(); // Handle shutdown process.on('SIGINT', async () => { await server.stop(); }); ``` -------------------------------- ### Implement an MCP Server with STDIO Transport Source: https://mcp-framework.com/docs/introduction/Transports/stdio-transport Demonstrates how to set up and manage an MCPServer instance using the STDIO transport. This example includes server initialization, asynchronous start and stop methods, and robust signal handling for graceful shutdown. ```typescript import { MCPServer } from "mcp-framework"; class MyMCPServer { private server: MCPServer; constructor() { this.server = new MCPServer({ name: "my-mcp-server", version: "1.0.0", transport: { type: "stdio" } }); // Handle process signals process.on('SIGINT', () => this.shutdown()); process.on('SIGTERM', () => this.shutdown()); } async start() { try { await this.server.start(); console.error('Server started successfully'); // Use stderr for logging } catch (error) { console.error('Failed to start server:', error); process.exit(1); } } private async shutdown() { console.error('Shutting down...'); try { await this.server.stop(); process.exit(0); } catch (error) { console.error('Error during shutdown:', error); process.exit(1); } } } // Start the server new MyMCPServer().start().catch(console.error); ``` -------------------------------- ### Troubleshoot Module Resolution Error Source: https://mcp-framework.com/docs/introduction/installation Example of a module resolution error indicating a missing peer dependency, typically resolved by installing the '@modelcontextprotocol/sdk' package. ```Text Error: Cannot find module '@modelcontextprotocol/sdk' ``` -------------------------------- ### Configure Claude Desktop for MCP Server Source: https://mcp-framework.com/docs/introduction/quickstart Adds a new MCP server configuration to the Claude Desktop client's `claude_desktop_config.json` file, specifying how to run the 'weather-mcp-server' using Node.js. ```json { "mcpServers": { "weather-mcp-server": { "command": "node", "args": ["/absolute/path/to/weather-mcp-server/dist/index.js"] } } } ``` -------------------------------- ### Configure MCP Server for HTTP Stream Transport Source: https://mcp-framework.com/docs/introduction/http-quickstart Illustrates the `src/index.ts` configuration for an MCP server. This code snippet sets up an `http-stream` transport on port 1337 with CORS enabled for all origins, initializing and starting the MCP server. ```typescript import { MCPServer } from "mcp-framework"; const server = new MCPServer({ transport: { type: "http-stream", options: { port: 1337, cors: { allowOrigin: "*" } } } }); server.start(); ``` -------------------------------- ### Add New MCP Tool Source: https://mcp-framework.com/docs/introduction/quickstart Generates a new tool file named 'weather' within the current MCP project, creating `src/tools/WeatherTool.ts`. ```shell mcp add tool weather ``` -------------------------------- ### MCP Framework Default Project Structure Source: https://mcp-framework.com/docs/introduction/installation This snippet illustrates the directory structure created by the MCP Framework CLI for a new project, including source files, tools, and configuration. ```Text my-mcp-server/ ├── src/ │ ├── tools/ # MCP Tools directory │ │ └── ExampleTool.ts │ └── index.ts # Server entry point ├── package.json └── tsconfig.json ``` -------------------------------- ### Open MCP Framework Project in VSCode Source: https://mcp-framework.com/docs/introduction/installation Command to open the newly created MCP Framework project in Visual Studio Code. ```Shell code . ``` -------------------------------- ### Install MCP Framework Manually Source: https://mcp-framework.com/docs/introduction/installation This command installs the MCP Framework package into an existing project using npm. ```Shell npm install mcp-framework ``` -------------------------------- ### Add New MCP Tool via CLI Source: https://mcp-framework.com/docs/introduction/http-quickstart Uses the `mcp` CLI to generate a new tool file named 'weather'. This command creates the boilerplate for a new tool, which will be located at `src/tools/WeatherTool.ts`. ```bash mcp add tool weather ``` -------------------------------- ### Interact with Fiscal Data MCP Server via Claude Desktop Source: https://mcp-framework.com/docs/introduction/Examples/fiscal-data Shows an example user interaction with the configured 'fiscal-data' MCP server through Claude Desktop. This prompt demonstrates how a user can request a treasury statement for a specific date, highlighting the natural language interface. ```User Prompt User: Can you get the treasury statement for the 20th of September 2023? ``` -------------------------------- ### Create New HTTP MCP Project Source: https://mcp-framework.com/docs/introduction/http-quickstart Uses the `mcp` CLI to create a new project named 'weather-http-server'. It configures the project to use the HTTP Stream Transport on port 1337 and enables CORS. The command then navigates into the newly created project directory. ```bash mcp create weather-http-server --http --port 1337 --cors cd weather-http-server ``` -------------------------------- ### Initialize MCP Server with STDIO Transport Source: https://mcp-framework.com/docs/introduction/Transports/stdio-transport Demonstrates how to initialize an MCP server, showing both the default STDIO transport and explicit configuration. The server is then started, making it ready to process messages via standard input/output. ```javascript import { MCPServer } from "mcp-framework"; // STDIO is the default transport const server = new MCPServer(); // Or explicitly specify STDIO transport const server = new MCPServer({ transport: { type: "stdio" } }); await server.start(); ``` -------------------------------- ### Troubleshoot TypeScript Error TS2304 Source: https://mcp-framework.com/docs/introduction/installation Example of a TypeScript error (TS2304) indicating a missing type definition, typically resolved by installing the 'zod' package. ```TypeScript error TS2304: Cannot find name 'z' ``` -------------------------------- ### Define Weather Tool Logic Source: https://mcp-framework.com/docs/introduction/quickstart Defines the `WeatherTool` class, extending `MCPTool`. It specifies the tool's name, description, input schema using Zod for validation, and an `execute` method that simulates fetching weather data for a given city. ```typescript import { MCPTool } from "mcp-framework"; import { z } from "zod"; interface WeatherInput { city: string; } class WeatherTool extends MCPTool { name = "weather"; description = "Get weather information for a city"; schema = { city: { type: z.string(), description: "City name to get weather for", }, }; async execute({ city }: WeatherInput) { // In a real scenario, this would call a weather API // For now, we return this sample data return { city, temperature: 22, condition: "Sunny", humidity: 45, }; } } export default WeatherTool; ``` -------------------------------- ### Implement Weather Tool for MCP Server Source: https://mcp-framework.com/docs/introduction/http-quickstart Defines a `WeatherTool` class extending `MCPTool` to handle weather requests. It specifies an input schema using Zod for the 'city' parameter and provides a sample `execute` method that returns mock weather data, simulating an external API call. ```typescript import { MCPTool } from "mcp-framework"; import { z } from "zod"; interface WeatherInput { city: string; } class WeatherTool extends MCPTool { name = "weather"; description = "Get weather information for a city"; schema = { city: { type: z.string(), description: "City name to get weather for", }, }; async execute({ city }: WeatherInput) { // In a real scenario, this would call a weather API // For now, we return this sample data return { city, temperature: 22, condition: "Sunny", humidity: 45, }; } } export default WeatherTool; ``` -------------------------------- ### Configure Basic MCP Server Settings Source: https://mcp-framework.com/docs/introduction/server-configuration This code snippet demonstrates the basic configuration of an `MCPServer` instance, including setting its name, version, base path for tools/prompts/resources, and initial transport configuration. It shows how to instantiate the server with essential parameters for a quick setup. ```typescript import { MCPServer } from "@modelcontextprotocol/mcp-framework"; const server = new MCPServer({ name: "my-mcp-server", // Server name version: "1.0.0", // Server version basePath: "./dist", // Base path for tools/prompts/resources transport: { // Transport configuration type: "sse", options: { // Transport-specific options } } }); ``` -------------------------------- ### Generate Treasury Report using MCP Framework Prompt Source: https://mcp-framework.com/docs/introduction/Examples/fiscal-data Illustrates how to use the `daily_treasury_report` prompt in the MCP Framework to generate a formatted treasury report. The example shows a user prompt requesting a report for a specific date, showcasing the report generation capability. ```User Prompt User: Generate a treasury report for 2024-03-01 ``` -------------------------------- ### Create a CLI Tool with STDIO Transport Source: https://mcp-framework.com/docs/introduction/Transports/stdio-transport An example of a Node.js command-line interface (CLI) tool that leverages MCP Framework's STDIO transport. This setup allows the MCP server to run as an integral part of the command-line application, handling communication via stdin/stdout. ```javascript #!/usr/bin/env node import { MCPServer } from "mcp-framework"; async function main() { const server = new MCPServer(); await server.start(); } main().catch(console.error); ``` -------------------------------- ### Create a static MCP Resource for documentation content Source: https://mcp-framework.com/docs/introduction/Resources/resources-overview Example of an `MCPResource` subclass designed to serve static documentation content, such as Markdown. The `read` method directly returns a predefined string as its content, making it suitable for embedding fixed informational texts. ```typescript class DocumentationResource extends MCPResource { uri = "resource://docs"; name = "Documentation"; mimeType = "text/markdown"; async read() { return [ { uri: this.uri, mimeType: this.mimeType, text: "# API Documentation\n\nWelcome to our API..." } ]; } } ``` -------------------------------- ### Configure MCP Server with HTTP Stream Transport Source: https://mcp-framework.com/docs/introduction/Transports/transports-overview This example illustrates how to set up an MCP server with the HTTP Stream transport. It includes common configuration options such as port, endpoint, response mode, CORS settings, and a placeholder for authentication configuration. ```JavaScript const server = new MCPServer({ transport: { type: "http-stream", options: { port: 8080, // Optional (default: 8080) endpoint: "/mcp", // Optional (default: "/mcp") responseMode: "batch", // Optional (default: "batch") cors: { allowOrigin: "*" // Optional CORS configuration }, auth: { // Optional authentication configuration } } } }); ``` -------------------------------- ### Perform Basic HTTP Requests with MCP Framework Source: https://mcp-framework.com/docs/introduction/Tools/api-integration Demonstrates how to make a basic HTTP GET request using the built-in `this.fetch` method within an MCPTool class to retrieve weather data. It shows how to use environment variables for API keys. ```typescript class WeatherTool extends MCPTool { async execute({ city }) { const API_KEY = process.env.WEATHER_API_KEY; const response = await this.fetch( `https://api.weather.com/v1/current/${city}?key=${API_KEY}` ); return response; } } ``` -------------------------------- ### Generate Structured Messages for Prompts Source: https://mcp-framework.com/docs/introduction/Prompts/prompts-overview Illustrates the asynchronous method for generating structured messages, including system and user roles with text content, which is crucial for guiding the AI model's behavior. ```JavaScript async generateMessages(input) { return [ { role: "system", content: { type: "text", text: "Context setting message" } }, { role: "user", content: { type: "text", text: "Main instruction" } } ]; } ``` -------------------------------- ### Configure MCP Fiscal Data Server for Claude Desktop Source: https://mcp-framework.com/docs/introduction/Examples/fiscal-data Provides the JSON configuration snippet required to add the 'fiscal-data' MCP server to the Claude Desktop application. This configuration specifies the command and arguments ('npx fiscal-data-mcp') needed for Claude Desktop to launch and interact with the server. ```JSON { "mcpServers": { "fiscal-data": { "command": "npx", "args": ["fiscal-data-mcp"] } } } ``` -------------------------------- ### Run MCP Inspector via npx Source: https://mcp-framework.com/docs/introduction/debugging Demonstrates how to run the MCP Inspector directly using `npx`, enabling quick debugging of an MCP server without a full installation. Replace `` with the compiled server entry point. ```shell npx @modelcontextprotocol/inspector ``` -------------------------------- ### Configure HTTP Stream Transport for Streaming Responses Source: https://mcp-framework.com/docs/introduction/http-quickstart This configuration snippet sets the `responseMode` to 'stream' within the `http-stream` transport options. This enables streaming responses for each request, as opposed to batching them, which is useful for real-time data flows and long-running operations. ```JSON transport: { type: "http-stream", options: { responseMode: "stream" // For streaming responses } } ``` -------------------------------- ### Client API Key Header Example Source: https://mcp-framework.com/docs/introduction/Authentication/overview Shows how a client should include the API key in the specified HTTP header (defaulting to 'X-API-Key') when making requests to an authenticated endpoint secured by API Key authentication. ```text X-API-Key: your-api-key-1 ``` -------------------------------- ### Define a basic MCPPrompt for personalized greetings Source: https://mcp-framework.com/docs/introduction/Prompts/prompts-overview This TypeScript example demonstrates how to define a simple `MCPPrompt` class. It includes an input interface, a `zod` schema for validation, and a `generateMessages` method to create AI-friendly content based on user input. ```typescript import { MCPPrompt } from "mcp-framework"; import { z } from "zod"; interface GreetingPromptInput { userName: string; timeOfDay: string; } class GreetingPrompt extends MCPPrompt { name = "greeting"; description = "Generates a personalized greeting"; schema = { userName: { type: z.string(), description: "User's name", required: true, }, timeOfDay: { type: z.enum(["morning", "afternoon", "evening"]), description: "Time of day", required: true, }, }; async generateMessages({ userName, timeOfDay }) { return [ { role: "user", content: { type: "text", text: `Good ${timeOfDay} ${userName}! How can I assist you today?`, }, }, ]; } } ``` -------------------------------- ### Client JWT Authorization Header Example Source: https://mcp-framework.com/docs/introduction/Authentication/overview Demonstrates how a client should include the JWT token in the 'Authorization' header with the 'Bearer' prefix when authenticating with a JWT-secured endpoint. ```text Authorization: Bearer eyJhbGciOiJIUzI1NiIs... ``` -------------------------------- ### Enable Stream Resumability for HTTP Stream Transport Source: https://mcp-framework.com/docs/introduction/http-quickstart This configuration snippet enables stream resumability for the `http-stream` transport. It sets a `historyDuration` of 5 minutes (300000 milliseconds), allowing clients to resume interrupted streams within this timeframe, significantly improving reliability and user experience in unstable network conditions. ```JSON transport: { type: "http-stream", options: { resumability: { enabled: true, historyDuration: 300000 // 5 minutes in milliseconds } } } ``` -------------------------------- ### Implement Input Validation Schema for Prompts Source: https://mcp-framework.com/docs/introduction/Prompts/prompts-overview Shows how to define a Zod schema for input validation, ensuring data integrity for prompt parameters. This example validates an email address. ```JavaScript schema = { email: { type: z.string().email(), description: "Valid email address", required: true, }, }; ``` -------------------------------- ### Integrate Logging in MCP Framework Tools Source: https://mcp-framework.com/docs/introduction/debugging Provides a JavaScript example demonstrating how to use the `logger` from `mcp-framework` within a custom `MCPTool`. It shows logging `info` messages for execution flow and `error` messages for exceptions, crucial for understanding tool behavior during debugging. ```javascript import { logger } from "mcp-framework"; class MyTool extends MCPTool { async execute(input) { logger.info("Starting execution"); try { const result = await this.process(input); logger.info("Execution successful"); return result; } catch (error) { logger.error("Execution failed:", error); throw error; } } } ``` -------------------------------- ### Integrate resources into MCPPrompt messages Source: https://mcp-framework.com/docs/introduction/Prompts/prompts-overview This TypeScript example shows how an `MCPPrompt` can utilize external resources. It demonstrates reading data using a `DatasetResource` and embedding that data as a `resource` object within the AI message content, allowing the AI to process external files. ```typescript class DataAnalysisPrompt extends MCPPrompt { async generateMessages({ datasetId }) { const dataResource = new DatasetResource(datasetId); const [data] = await dataResource.read(); return [ { role: "user", content: { type: "text", text: "Please analyze this dataset:", resource: { uri: data.uri, text: data.text, mimeType: data.mimeType, }, }, }, ]; } } ``` -------------------------------- ### Integrate with GitHub API using MCPTool and Zod Schema Source: https://mcp-framework.com/docs/introduction/Tools/api-integration A complete example demonstrating how to create an MCPTool to fetch GitHub repository star counts. It includes defining input schema with Zod, handling authentication headers, making API calls, processing responses, and robust error handling. ```typescript import { MCPTool } from "mcp-framework"; import { z } from "zod"; interface GitHubInput { username: string; repo: string; } class GitHubStarsTool extends MCPTool { name = "github-stars"; description = "Get star count for a GitHub repository"; schema = { username: { type: z.string(), description: "GitHub username", }, repo: { type: z.string(), description: "Repository name", }, }; private headers = { Authorization: `token ${process.env.GITHUB_TOKEN}`, Accept: "application/vnd.github.v3+json", }; async execute({ username, repo }) { try { const response = await this.fetch( `https://api.github.com/repos/${username}/${repo}`, { headers: this.headers } ); if (!response.ok) { throw new Error(`GitHub API Error: ${response.status}`); } const data = await response.json(); return { stars: data.stargazers_count, url: data.html_url, description: data.description, }; } catch (error) { throw new Error(`Failed to fetch repo data: ${error.message}`); } } } export default GitHubStarsTool; ``` -------------------------------- ### Define MCPPrompt input schema with Zod Source: https://mcp-framework.com/docs/introduction/Prompts/prompts-overview This TypeScript example shows how to define the `schema` property for an `MCPPrompt` using `zod`. It specifies the expected input parameters, their types, descriptions, and whether they are required, enabling robust input validation. ```typescript schema = { dataset: { type: z.string(), description: "Dataset to analyze", required: true, }, metrics: { type: z.array(z.string()), description: "Metrics to calculate", required: true, }, }; ``` -------------------------------- ### Configure Custom Headers for SSE Responses Source: https://mcp-framework.com/docs/introduction/Transports/sse This example shows how to add custom HTTP headers to the SSE transport configuration. These headers will be included in the responses sent by the SSE server. ```typescript headers: { "X-Custom-Header": "value", "Cache-Control": "no-cache" } ``` -------------------------------- ### Configure Authentication for SSE Transport Endpoints Source: https://mcp-framework.com/docs/introduction/Transports/sse This example demonstrates how to integrate an authentication provider with the SSE transport. It shows how to specify whether authentication is required for SSE connections and message endpoints, ensuring secure access to the transport's functionalities. ```typescript auth: { provider: authProvider, // Authentication provider instance endpoints: { sse: true, // Require auth for SSE connections messages: true // Require auth for messages } } ``` -------------------------------- ### Initialize MCPServer with SSE Transport Configuration Source: https://mcp-framework.com/docs/introduction/Transports/sse This snippet demonstrates how to set up an MCPServer instance using the SSE transport type. It includes a comprehensive example of configuring various options such as the listening port, SSE and message endpoints, maximum message size, custom HTTP headers, Cross-Origin Resource Sharing (CORS) settings, and authentication requirements for different endpoints. ```typescript import { MCPServer } from "@modelcontextprotocol/mcp-framework"; const server = new MCPServer({ transport: { type: "sse", options: { port: 8080, // Port to listen on (default: 8080) endpoint: "/sse", // SSE endpoint path (default: "/sse") messageEndpoint: "/messages", // Message endpoint path (default: "/messages") maxMessageSize: "4mb", // Maximum message size (default: "4mb") headers: { // Custom headers for SSE responses "X-Custom-Header": "value" }, cors: { // CORS configuration allowOrigin: "*", allowMethods: "GET, POST, OPTIONS", allowHeaders: "Content-Type, Authorization, x-api-key", exposeHeaders: "Content-Type, Authorization, x-api-key", maxAge: "86400" }, auth: { // Authentication configuration provider: authProvider, endpoints: { sse: true, // Require auth for SSE connections messages: true // Require auth for messages } } } } }); ``` -------------------------------- ### Example Error Response for Invalid API Key Source: https://mcp-framework.com/docs/introduction/Authentication/overview Illustrates the JSON structure of an error response returned by the MCP Framework when an invalid API key is provided. It includes the error message, HTTP status code, and error type. ```json { "error": "Invalid API key", "status": 401, "type": "authentication_error" } ``` -------------------------------- ### Create MCP Project with HTTP Transport via CLI Source: https://mcp-framework.com/docs/introduction/Transports/http-stream-transport This CLI command demonstrates how to use the `mcp` command-line interface to scaffold a new MCP project. It configures the project to use HTTP transport, specifies a custom port, and enables CORS, streamlining project setup. ```bash mcp create my-mcp-server --http --port 1337 --cors ``` -------------------------------- ### Configure HTTP Stream Transport Session Management Source: https://mcp-framework.com/docs/introduction/http-quickstart This configuration snippet enables session management for the `http-stream` transport. It specifies a custom header name for the session ID (`Mcp-Session-Id`) and allows client-side session termination, enhancing control over user sessions and state persistence. ```JSON transport: { type: "http-stream", options: { session: { enabled: true, headerName: "Mcp-Session-Id", allowClientTermination: true } } } ``` -------------------------------- ### Fetch Daily Treasury Statement using MCP Framework Tool Source: https://mcp-framework.com/docs/introduction/Examples/fiscal-data Demonstrates how to use the `get_daily_treasury_statement` tool within the MCP Framework by providing a user prompt to retrieve treasury data for a specific date. This interaction simulates a user query to the configured MCP server. ```User Prompt User: Get the treasury statement for 2024-03-01 ``` -------------------------------- ### Example Error Response for Invalid JWT Source: https://mcp-framework.com/docs/introduction/Authentication/overview Shows the JSON structure of an error response returned by the MCP Framework for an invalid or expired JWT token, detailing the error message, HTTP status code, and error type. ```json { "error": "Invalid or expired JWT token", "status": 401, "type": "authentication_error" } ``` -------------------------------- ### Implement Robust API Error Handling in MCPTool Source: https://mcp-framework.com/docs/introduction/Tools/api-integration Provides an example of comprehensive error handling for API requests, including checking `response.ok`, catching network errors (`TypeError`), and request timeouts (`AbortError`). It demonstrates how to throw specific errors for different failure scenarios. ```typescript class RobustApiTool extends MCPTool { async execute(input) { try { const response = await this.fetch("https://api.example.com/data"); if (!response.ok) { throw new Error(`API Error: ${response.status}`); } return response.json(); } catch (error) { if (error.name === "AbortError") { throw new Error("Request timed out"); } if (error.name === "TypeError") { throw new Error("Network error"); } throw error; } } } ``` -------------------------------- ### JSON-RPC Standard Error Response Format Source: https://mcp-framework.com/docs/introduction/Transports/http-stream-transport Example of a standard JSON-RPC error response, including the protocol version, request ID, and a detailed error object with code, message, and an optional data field for additional information. ```json { "jsonrpc": "2.0", "id": "request-id", "error": { "code": -32000, "message": "Error message", "data": { // Additional error information } } } ``` -------------------------------- ### Configure MCP Server with Basic HTTP Stream Transport Source: https://mcp-framework.com/docs/introduction/Transports/http-stream-transport This JavaScript code snippet shows a simplified configuration for the `MCPServer` using the HTTP Stream Transport. It sets the listening port and enables basic CORS for all origins, providing a quick setup for common use cases. ```javascript import { MCPServer } from "mcp-framework"; const server = new MCPServer({ transport: { type: "http-stream", options: { port: 8080, cors: { allowOrigin: "*" } } } }); await server.start(); ``` -------------------------------- ### Ensure Type Safety in MCP Tool with Zod Source: https://mcp-framework.com/docs/introduction/Tools/tools-overview This example demonstrates how MCP Framework leverages TypeScript interfaces and Zod schemas to enforce end-to-end type safety for tool inputs. It shows how to define an input interface and then map its properties to a Zod schema for robust validation. ```TypeScript interface DataInput { userId: number; fields: string[]; } class DataTool extends MCPTool { schema = { userId: { type: z.number(), description: "User ID to fetch data for", }, fields: { type: z.array(z.string()), description: "Fields to include in response", }, }; } ``` -------------------------------- ### Best Practice: Add Descriptive Input Validation Source: https://mcp-framework.com/docs/introduction/Tools/tools-overview This snippet demonstrates the best practice of adding descriptive input validation to an MCP Tool's schema. Using Zod, it shows how to define validation rules (e.g., 'min', 'max') and provide a clear 'description' for each input field, guiding both developers and AI models on expected input ranges and formats. ```TypeScript schema = { age: { type: z.number().min(0).max(150), description: "User's age (0-150)", }, }; ``` -------------------------------- ### Implement Robust Error Handling in MCP Tool Source: https://mcp-framework.com/docs/introduction/Tools/tools-overview This snippet provides an example of best practices for error handling within an MCP Tool's 'execute' method. It uses a 'try-catch' block to gracefully manage potential errors, demonstrating how to catch specific error types and rethrow more descriptive errors for better debugging and AI model feedback. ```TypeScript async execute(input: MyInput) { try { const result = await this.processData(input); return result; } catch (error) { if (error.code === 'NETWORK_ERROR') { throw new Error('Unable to reach external service'); } throw new Error(`Operation failed: ${error.message}`); } } ``` -------------------------------- ### Define a basic MCP Resource for static configuration Source: https://mcp-framework.com/docs/introduction/Resources/resources-overview Demonstrates how to create a simple `MCPResource` subclass to serve static configuration data. It defines standard resource metadata (URI, name, description, MIME type) and implements an asynchronous `read` method to return a hardcoded JSON string as its content. ```typescript import { MCPResource } from "mcp-framework"; class ConfigResource extends MCPResource { uri = "resource://config"; name = "Configuration"; description = "System configuration settings"; mimeType = "application/json"; async read() { return [ { uri: this.uri, mimeType: this.mimeType, text: JSON.stringify({ version: "1.0.0", environment: "production", features: ["analytics", "reporting"] }) } ]; } } ``` -------------------------------- ### Generate MCP Tool Template via CLI Source: https://mcp-framework.com/docs/introduction/Tools/tools-overview This command-line snippet shows the fastest way to create a new tool in the MCP Framework by using the 'mcp add tool' command, which generates a tool template file. ```Shell mcp add tool my-tool ``` -------------------------------- ### Best Practice: Use Clear Tool Names Source: https://mcp-framework.com/docs/introduction/Tools/tools-overview This snippet illustrates a best practice for naming MCP Tools, emphasizing the importance of clear and descriptive names (e.g., "fetch-user-data") over ambiguous abbreviations (e.g., "fud"). Clear names improve readability for both developers and AI models. ```TypeScript name = "fetch-user-data"; // Good name = "fud"; // Bad ``` -------------------------------- ### Define Prompt Name Clearly Source: https://mcp-framework.com/docs/introduction/Prompts/prompts-overview Illustrates the best practice of using clear and descriptive names for prompts, avoiding abbreviations for better readability and understanding. ```JavaScript name = "financial-analysis"; // Good name = "fa"; // Bad ``` -------------------------------- ### Best Practice: Provide Detailed Tool Descriptions Source: https://mcp-framework.com/docs/introduction/Tools/tools-overview This snippet highlights the importance of providing detailed descriptions for MCP Tools. A comprehensive description helps AI models understand the tool's capabilities and ensures proper usage, going beyond a simple summary to include specific functionalities. ```TypeScript description = "Fetches user data including profile, preferences, and settings"; ``` -------------------------------- ### Create a multi-step MCPPrompt with system and user roles Source: https://mcp-framework.com/docs/introduction/Prompts/prompts-overview This TypeScript snippet illustrates a multi-step `MCPPrompt` where messages are generated with different roles. It includes a `system` message to set the AI's persona and a `user` message to provide specific instructions, enabling more complex conversational flows. ```typescript class ReportPrompt extends MCPPrompt { async generateMessages({ reportType }) { return [ { role: "system", content: { type: "text", text: "You are a professional report writer.", }, }, { role: "user", content: { type: "text", text: `Create a ${reportType} report using the following data:`, }, }, ]; } } ``` -------------------------------- ### Configure MCP Server with STDIO Transport Source: https://mcp-framework.com/docs/introduction/Transports/transports-overview This snippet demonstrates how to initialize an MCP server instance using the default STDIO transport. It shows both the implicit and explicit ways to specify the STDIO transport type during server creation. ```JavaScript const server = new MCPServer(); // or explicitly: const server = new MCPServer({ transport: { type: "stdio" } }); ``` -------------------------------- ### Generate new MCPPrompt using CLI Source: https://mcp-framework.com/docs/introduction/Prompts/prompts-overview This command-line interface (CLI) snippet shows how to quickly scaffold a new prompt file (`MyPrompt.ts`) within the `src/prompts` directory of an MCP Framework project. ```bash mcp add prompt my-prompt ``` -------------------------------- ### Define a Basic MCP Tool for Greetings Source: https://mcp-framework.com/docs/introduction/Tools/tools-overview This snippet demonstrates the basic structure of an MCP Tool, showing how to define inputs using an interface, specify 'name' and 'description', define a 'schema' with Zod for type validation, and implement the 'execute' method to perform the tool's logic. ```TypeScript import { MCPTool } from "mcp-framework"; import { z } from "zod"; interface GreetingInput { name: string; language: string; } class GreetingTool extends MCPTool { name = "greeting"; description = "Generate a greeting in different languages"; schema = { name: { type: z.string(), description: "Name to greet", }, language: { type: z.enum(["en", "es", "fr"]), description: "Language code (en, es, fr)", }, }; async execute({ name, language }) { const greetings = { en: `Hello ${name}!`, es: `¡Hola ${name}!`, fr: `Bonjour ${name}!`, }; return greetings[language]; } } ``` -------------------------------- ### Implement Report Generator Prompt Class Source: https://mcp-framework.com/docs/introduction/Prompts/prompts-overview Defines a `ReportGeneratorPrompt` class extending `MCPPrompt`, showcasing how to set up prompt name, description, a complex input schema with Zod for report data and format, and the `generateMessages` method for dynamic report generation based on user input. ```JavaScript class ReportGeneratorPrompt extends MCPPrompt { name = "report-generator"; description = "Generates formatted reports from data"; schema = { data: { type: z.object({ title: z.string(), sections: z.array(z.string()), }), description: "Report data structure", }, format: { type: z.enum(["short", "detailed"]), description: "Report format", }, }; async generateMessages({ data, format }) { return [ { role: "user", content: { type: "text", text: `Generate a ${format} report titled "${ data.title }" with the following sections: ${data.sections.join(", ")}`, }, }, ]; } } ``` -------------------------------- ### Configure MCPServer with SSE Transport Source: https://mcp-framework.com/docs/introduction/Transports/transports-overview This JavaScript code snippet demonstrates how to initialize an MCPServer instance, specifying 'sse' as the transport type. It includes optional configuration parameters for the SSE transport, such as the listening port, the SSE endpoint, the message endpoint, and a placeholder for authentication settings. ```javascript const server = new MCPServer({ transport: { type: "sse", options: { port: 8080, // Optional (default: 8080) endpoint: "/sse", // Optional (default: "/sse") messageEndpoint: "/messages", // Optional (default: "/messages") auth: { // Optional authentication configuration } } } }); ``` -------------------------------- ### Add a new MCP Resource using the CLI Source: https://mcp-framework.com/docs/introduction/Resources/resources-overview Shows the command-line interface (CLI) command to quickly generate a new resource file within the MCP Framework project structure. This command automates the creation of a boilerplate resource class in the `src/resources/` directory. ```bash mcp add resource my-resource ``` -------------------------------- ### Combine MCP Resources with Tools for Data Processing Source: https://mcp-framework.com/docs/introduction/Resources/resources-overview Demonstrates how to integrate an 'MCPResource' (DataResource) with an 'MCPTool' (DataProcessor). The tool reads data from the resource, parses it, and then processes it, showcasing inter-component communication and advanced data flow within the framework. ```javascript class DataResource extends MCPResource { uri = "resource://data"; name = "Data Store"; async read() { return [ { uri: this.uri, mimeType: "application/json", text: JSON.stringify(await this.getData()), }, ]; } } class DataProcessor extends MCPTool { async execute(input) { const resource = new DataResource(); const [data] = await resource.read(); return this.processData(JSON.parse(data.text)); } } ``` -------------------------------- ### Provide Detailed Prompt Description Source: https://mcp-framework.com/docs/introduction/Prompts/prompts-overview Demonstrates the importance of providing a comprehensive description for a prompt, outlining its purpose and the specific metrics or insights it provides. ```JavaScript description = "Analyzes financial data and provides insights with specific metrics"; ``` -------------------------------- ### Define Resource URI Naming Convention Source: https://mcp-framework.com/docs/introduction/Resources/resources-overview Demonstrates the recommended URI naming convention for resources in the MCP Framework, following a 'resource://domain/type/identifier' pattern for consistent resource identification. ```javascript uri = "resource://domain/type/identifier"; // Example: "resource://finance/stocks/AAPL" ``` -------------------------------- ### JavaScript Client for SSE Transport Implementation Source: https://mcp-framework.com/docs/introduction/Transports/sse This JavaScript code demonstrates how to build a client for the SSE transport. It covers establishing an `EventSource` connection, listening for 'endpoint' events to retrieve the message sending URL, handling 'message' events to process incoming data, and an asynchronous `sendMessage` function using `fetch` to send JSON payloads to the server, including error handling and optional authentication. ```JavaScript // Establish SSE connection const eventSource = new EventSource('http://localhost:8080/sse'); // Handle endpoint URL eventSource.addEventListener('endpoint', (event) => { const messageEndpoint = event.data; // Store messageEndpoint for sending messages }); // Handle messages eventSource.addEventListener('message', (event) => { const message = JSON.parse(event.data); // Process message }); // Send message async function sendMessage(message) { const response = await fetch(messageEndpoint, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer your-token' // If using authentication }, body: JSON.stringify(message) }); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } } ``` -------------------------------- ### Develop a real-time MCP Resource with WebSocket subscriptions Source: https://mcp-framework.com/docs/introduction/Resources/resources-overview Illustrates an `MCPResource` designed for handling real-time data streams using WebSockets. It includes `subscribe` and `unsubscribe` methods to manage the WebSocket connection lifecycle and an `on message` handler for processing incoming updates, enabling continuous data flow. ```typescript class StockTickerResource extends MCPResource { uri = "resource://stock-ticker"; name = "Stock Ticker"; mimeType = "application/json"; private ws: WebSocket | null = null; async subscribe() { this.ws = new WebSocket("wss://stocks.example.com"); this.ws.on("message", this.handleUpdate); } async unsubscribe() { if (this.ws) { this.ws.close(); this.ws = null; } } async read() { const latestData = await this.getLatestStockData(); return [ { uri: this.uri, mimeType: this.mimeType, text: JSON.stringify(latestData) } ]; } } ``` -------------------------------- ### Implement a dynamic MCP Resource fetching external API data Source: https://mcp-framework.com/docs/introduction/Resources/resources-overview Demonstrates an `MCPResource` that fetches data dynamically from an external API endpoint. The `read` method uses an asynchronous `fetch` call to retrieve the latest market data, which is then processed and returned as JSON content, showcasing real-time data integration. ```typescript class MarketDataResource extends MCPResource { uri = "resource://market-data"; name = "Market Data"; mimeType = "application/json"; async read() { const data = await this.fetch("https://api.market.com/latest"); return [ { uri: this.uri, mimeType: this.mimeType, text: JSON.stringify(data) } ]; } } ``` -------------------------------- ### Configure MCP Server Logging Source: https://mcp-framework.com/docs/introduction/server-configuration This snippet illustrates how to import and utilize the built-in `logger` from the MCP Framework. It demonstrates logging messages at various levels: `debug`, `info`, `warn`, and `error`, providing a flexible way to control and monitor server output. ```typescript import { logger } from "@modelcontextprotocol/mcp-framework"; // Log levels: debug, info, warn, error logger.debug("Debug message"); logger.info("Info message"); logger.warn("Warning message"); logger.error("Error message"); ``` -------------------------------- ### Configure MCP Server with Full HTTP Stream Transport Options Source: https://mcp-framework.com/docs/introduction/Transports/http-stream-transport This JavaScript code snippet demonstrates how to initialize an `MCPServer` instance with comprehensive configuration options for the HTTP Stream Transport. It includes settings for port, endpoint, response mode, message size, batch timeout, custom headers, CORS, authentication, session management, and stream resumability. ```javascript import { MCPServer } from "mcp-framework"; const server = new MCPServer({ transport: { type: "http-stream", options: { port: 8080, // Port to listen on (default: 8080) endpoint: "/mcp", // HTTP endpoint path (default: "/mcp") responseMode: "batch", // Response mode: "batch" or "stream" (default: "batch") maxMessageSize: "4mb", // Maximum message size (default: "4mb") batchTimeout: 30000, // Timeout for batch responses in ms (default: 30000) headers: { // Custom headers for responses "X-Custom-Header": "value" }, cors: { // CORS configuration allowOrigin: "*", allowMethods: "GET, POST, DELETE, OPTIONS", allowHeaders: "Content-Type, Accept, Authorization, x-api-key, Mcp-Session-Id, Last-Event-ID", exposeHeaders: "Content-Type, Authorization, x-api-key, Mcp-Session-Id", maxAge: "86400" }, auth: { // Authentication configuration provider: authProvider }, session: { // Session configuration enabled: true, // Enable session management (default: true) headerName: "Mcp-Session-Id", // Session header name (default: "Mcp-Session-Id") allowClientTermination: true // Allow clients to terminate sessions (default: true) }, resumability: { // Stream resumability configuration enabled: false, // Enable stream resumability (default: false) historyDuration: 300000 // How long to keep message history in ms (default: 300000 - 5 minutes) } } } }); await server.start(); ``` -------------------------------- ### Initialize API Key Authentication Provider Source: https://mcp-framework.com/docs/introduction/Authentication/overview Demonstrates how to create an APIKeyAuthProvider instance with a list of valid API keys and an optional custom header name. This provider secures endpoints using predefined keys, suitable for simple authentication scenarios. ```javascript import { APIKeyAuthProvider } from "@modelcontextprotocol/mcp-framework"; const authProvider = new APIKeyAuthProvider({ keys: ["your-api-key-1", "your-api-key-2"], headerName: "X-API-Key" // Optional, defaults to "X-API-Key" }); ```