### Project Setup and Start Commands Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/docs/docs-package/cli.md Commands to navigate into the project directory, set up environment variables, build the project, and start the documentation server. ```bash cd my-api-docs cp .env.example .env # Edit .env with your documentation site URL npm run build npm start ``` -------------------------------- ### Quick Start: Initialize Client and List Users Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/packages/docs/tests/fixtures/llms-full-txt-simple.txt Initialize the MyAPI client with your API key and fetch a list of users. This is a basic example to get started. ```typescript import { MyAPI } from 'myapi-sdk'; const client = new MyAPI({ apiKey: 'your-api-key' }); const users = await client.users.list(); console.log(users); ``` -------------------------------- ### Minimal Server Setup Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/_autodocs/QUICK_REFERENCE.md Set up a minimal MCP server instance and start it. ```typescript import { MCPServer } from "mcp-framework"; // Minimal setup const server = new MCPServer(); await server.start(); ``` -------------------------------- ### Run Simple OAuth Example Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/examples/README.md Builds and runs a basic OAuth integration example. Use this to understand the fundamental setup and callback handling in the MCP Framework. ```bash npm run build node dist/examples/oauth-simple-example.js ``` -------------------------------- ### Initialize MCPServer with SATPProvider Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/docs/docs-package/satp-agent-trust.md Quick start example for setting up the MCPServer with SATPProvider for agent trust verification. No API keys are needed as the AgentFolio API is public. ```typescript import { MCPServer, SATPProvider } from "mcp-framework"; const server = new MCPServer({ auth: { provider: new SATPProvider({ minTrustScore: 50, onMissing: "allow", // Don't break unidentified agents }), }, }); ``` -------------------------------- ### Install Dependencies Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/examples/README.md Installs project dependencies using npm. This is a prerequisite for building and running the examples. ```bash npm install ``` -------------------------------- ### start() Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/_autodocs/api-reference/MCPServer.md Starts the MCP server, loading necessary components like tools, prompts, and resources. This method should be called after the server instance is created and configured. ```APIDOC ## start() ### Description Starts the MCP server with configured transports. Loads tools, prompts, and resources from the base path. ### Method `async start(): Promise` ### Returns - `Promise` - A promise that resolves when the server startup is complete. ### Throws - `Error` - If transport configuration is invalid or startup fails. ### Example ```typescript const server = new MCPServer({ name: "my-server", version: "1.0.0" }); await server.start(); ``` ``` -------------------------------- ### Run Example Server with Cognito Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/OAUTH_QUICK_START.md Environment variables and commands to build and run an example server using AWS Cognito for OAuth authentication. ```bash # Cognito example export COGNITO_DOMAIN="your-domain.auth.us-east-1.amazoncognito.com" export COGNITO_CLIENT_ID="your-client-id" export COGNITO_CLIENT_SECRET="your-client-secret" export RESOURCE_URI="https://mcp.example.com" npm run build node dist/examples/oauth-cognito-example.js ``` -------------------------------- ### Environment Variables Example Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/docs/docs-package/cli.md An example `.env` file showing the variables required for configuring the documentation server, including base URL and optional API key. ```bash DOCS_BASE_URL=https://docs.example.com DOCS_SERVER_NAME=my-api-docs # DOCS_API_KEY=your-api-key-here ``` -------------------------------- ### MCP Server Startup Output Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/examples/README-COGNITO.md This is an example of the expected output when the MCP server starts with Cognito OAuth 2.1 configuration. It details the active configuration parameters. ```text 🚀 Starting MCP Server with Cognito OAuth 2.1 Configuration: Port: 8080 Region: us-west-2 User Pool: us-west-2_pJpps8NA4 Issuer: https://cognito-idp.us-west-2.amazonaws.com/us-west-2_pJpps8NA4 JWKS URI: https://cognito-idp.us-west-2.amazonaws.com/us-west-2_pJpps8NA4/.well-known/jwks.json Client ID: 1m3mpk6fioslohhl54the6ugoh Resource: https://mcp.example.com ✅ MCP Server started successfully! ``` -------------------------------- ### Install and Create MCP Server Project Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/README.md Install the MCP framework globally and create a new MCP server project using the CLI. Navigate into the created project directory. ```bash npm install -g mcp-framework mcp create my-mcp-server cd my-mcp-server ``` -------------------------------- ### Install and Use Official SDK Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/docs/apps.md Install the `@modelcontextprotocol/ext-apps` package to build more complex applications. This snippet shows basic initialization and event handling. ```bash npm install @modelcontextprotocol/ext-apps ``` ```typescript import { App } from "@modelcontextprotocol/ext-apps"; const app = new App({ name: "my-app", version: "1.0.0" }); app.ontoolinput = (params) => { // Render tool arguments }; app.ontoolresult = (params) => { // Render results }; await app.connect(); ``` -------------------------------- ### Set OAuth Environment Variables for npm Start Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/_autodocs/configuration.md Example of setting OAuth environment variables before starting the application with npm. Ensure all required variables are defined. ```bash OAUTH_AUTHORIZATION_SERVER=https://auth.example.com \ OAUTH_RESOURCE=https://mcp.example.com \ OAUTH_JWKS_URI=https://auth.example.com/.well-known/jwks.json \ OAUTH_AUDIENCE=https://mcp.example.com \ OAUTH_ISSUER=https://auth.example.com \ npm start ``` -------------------------------- ### Example Implementation of subscribe() Method Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/_autodocs/api-reference/MCPResource.md An example of implementing the subscribe() method to watch for file changes and notify subscribers. ```typescript private watcher: any; async subscribe() { this.watcher = watch('./data.json', () => { this.notifySubscribers(); }); } ``` -------------------------------- ### complete Method Example Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/_autodocs/api-reference/MCPPrompt.md An example implementation of the complete method for providing argument completion suggestions. This specific example offers predefined values for a 'category' argument. ```typescript async complete(argumentName: string, value: string) { if (argumentName === 'category') { return { values: ['technology', 'science', 'health', 'business'], hasMore: false }; } return { values: [] }; } ``` -------------------------------- ### Example Prompt Implementation Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/_autodocs/api-reference/MCPPrompt.md An example implementation of an MCPPrompt, defining its name, description, schema with topic and style arguments, and the generateMessages method. ```typescript class MyPrompt extends MCPPrompt<{ topic: string; style: string }> { name = "analysis_prompt"; description = "Analyzes a topic in a specific style"; protected schema = { topic: { type: z.string(), description: "The topic to analyze", required: true }, style: { type: z.enum(['formal', 'casual', 'academic']), description: "Writing style", required: false } }; protected async generateMessages(args: { topic: string; style: string }) { return [ { role: "user", content: { type: "text", text: `Analyze "${args.topic}" in ${args.style} style.` } } ]; } } ``` -------------------------------- ### OAuth Example Server Structure Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/OAUTH_IMPLEMENTATION_PLAN.md Defines the file structure for an example OAuth server implementation. ```tree examples/oauth-server/ ├── index.ts ├── package.json ├── .env.example └── README.md ``` -------------------------------- ### Install MCP Framework Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/_autodocs/README.md Install the mcp-framework package using npm. ```bash npm install mcp-framework ``` -------------------------------- ### DocsServer Lifecycle Management Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/docs/docs-package/server.md Provides examples for starting and stopping the DocsServer programmatically. The server also handles SIGINT and SIGTERM for graceful shutdown. ```typescript // Start the server (blocks until shutdown signal) await server.start(); // Stop programmatically await server.stop(); ``` -------------------------------- ### OAuth Configuration Example Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/OAUTH_IMPLEMENTATION_PLAN.md Example environment variables for OAuth introspection validation. Uncomment and fill in your specific details. ```bash # For introspection validation (uncomment if needed) # OAUTH_VALIDATION_TYPE=introspection # OAUTH_INTROSPECTION_ENDPOINT=https://auth.example.com/oauth/introspect # OAUTH_CLIENT_ID=your-client-id # OAUTH_CLIENT_SECRET=your-client-secret ``` -------------------------------- ### Client API Key Authentication Header Example Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/README.md Example of how a client should format the header with an API key for API Key authentication. ```text X-API-Key: your-api-key ``` -------------------------------- ### Copy Environment File Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/examples/oauth-server/README.md Copy the example environment file to be configured for your OAuth provider. ```bash cp .env.example .env ``` -------------------------------- ### Install MyAPI SDK with npm Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/packages/docs/tests/fixtures/llms-full-txt-simple.txt Install the MyAPI SDK using npm. Ensure you have Node.js 18 or later. ```bash npm install myapi-sdk ``` -------------------------------- ### Resource Listing Example Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/docs/resources.md An example of the JSON response format for the `resources/list` protocol method. The framework automatically generates this based on registered resources. ```json { "resources": [ { "uri": "resource://config", "name": "Configuration", "description": "System configuration settings", "mimeType": "application/json" }, { "uri": "resource://market-data", "name": "Market Data", "description": "Live market data", "mimeType": "application/json" } ] } ``` -------------------------------- ### Run Cognito OAuth Example Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/examples/README.md Builds and runs a complete example for AWS Cognito integration. Requires setting environment variables for Cognito domain, client ID, client secret, resource URI, and port. ```bash # Set environment variables export COGNITO_DOMAIN="your-domain.auth.us-east-1.amazoncognito.com" export COGNITO_CLIENT_ID="your-client-id" export COGNITO_CLIENT_SECRET="your-client-secret" export RESOURCE_URI="https://mcp.example.com" export PORT=3001 # Run the example npm run build node dist/examples/oauth-cognito-example.js ``` -------------------------------- ### Install MyAPI SDK with yarn Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/packages/docs/tests/fixtures/llms-full-txt-simple.txt Install the MyAPI SDK using yarn. Ensure you have Node.js 18 or later. ```bash yarn add myapi-sdk ``` -------------------------------- ### Run OAuth Test Client Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/OAUTH_IMPLEMENTATION_SUMMARY.md Command to build the project and run the OAuth test client example. ```bash npm run build node dist/examples/oauth-test-client.js ``` -------------------------------- ### Instantiate MCPServer with Basic Configuration Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/_autodocs/api-reference/MCPServer.md Create a new MCPServer instance with a name and version. This is a basic setup for the server. ```typescript const server = new MCPServer({ name: "my-server", version: "1.0.0" }); await server.start(); ``` -------------------------------- ### Serverless Lambda Handler Example Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/_autodocs/configuration.md Example of setting up an MCPServer for a serverless Lambda environment. Demonstrates initializing the server with authentication configuration and exporting a handler function to process incoming events. ```typescript import { MCPServer } from "mcp-framework"; const server = new MCPServer({ name: "serverless-mcp", version: "1.0.0", auth: { provider: new APIKeyAuthProvider({ keys: [process.env.API_KEY] }) } }); export const handler = async (event, context) => { return server.handleRequest(event, context); }; ``` -------------------------------- ### Create an MCPServer Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/_autodocs/README.md Initialize and start an MCPServer instance. Tools are automatically discovered from the 'tools/' directory. ```typescript import { MCPServer } from "mcp-framework"; const server = new MCPServer({ name: "my-server", version: "1.0.0" }); await server.start(); ``` -------------------------------- ### Basic Server Logging Setup Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/_autodocs/api-reference/Logger.md Initialize an MCPServer with logging enabled and use the logger for startup and error messages. Ensure 'mcp-framework' is imported. ```typescript import { MCPServer } from 'mcp-framework'; import { logger } from 'mcp-framework'; const server = new MCPServer({ name: 'my-server', logging: true // Enable server logging }); logger.info('Server configuration loaded'); try { await server.start(); logger.info('Server started successfully'); } catch (error) { logger.error(`Server startup failed: ${error.message}`); process.exit(1); } ``` -------------------------------- ### Build and Run the Server Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/examples/oauth-server/README.md Build the project and start the MCP OAuth Server. The server will run on http://localhost:8080 by default. ```bash npm run build npm start ``` -------------------------------- ### Example Implementation of unsubscribe() Method Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/_autodocs/api-reference/MCPResource.md An example of implementing the unsubscribe() method to close the file watcher. ```typescript async unsubscribe() { if (this.watcher) { this.watcher.close(); this.watcher = null; } } ``` -------------------------------- ### Example Implementation of complete() Method Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/_autodocs/api-reference/MCPResource.md An example of implementing the complete() method to provide user ID suggestions for a URI template argument. ```typescript async complete(argumentName: string, value: string) { if (argumentName === 'userId') { const users = await fetchUserIds(); return { values: users, hasMore: false }; } return { values: [] }; } ``` -------------------------------- ### Initialize MCPServer Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/README.md Demonstrates the basic initialization of an `MCPServer` instance. This is the starting point for setting up the MCP server application. ```typescript import { MCPServer } from "mcp-framework"; const server = new MCPServer(); // Start the server await server.start(); ``` -------------------------------- ### Custom Tool Example with Authentication Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/examples/oauth-server/README.md Example of creating a custom tool that accesses authenticated user claims and performs scope-based authorization. ```typescript import { MCPTool, McpInput } from "mcp-framework"; import { z } from "zod"; const MyToolSchema = z.object({ input: z.string().describe("Your input parameter"), }); class MyTool extends MCPTool { name = "my_tool"; description = "My authenticated tool"; schema = MyToolSchema; async execute(input: McpInput, context?: any) { // Access authentication claims const claims = context?.auth?.data; const userId = claims?.sub; // Implement scope-based authorization if needed if (!claims?.scope?.includes('required:scope')) { throw new Error('Insufficient permissions'); } // Your tool logic here return `Processed for user ${userId}`; } } export default MyTool; ``` -------------------------------- ### OAuth Environment Variables Example Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/OAUTH_IMPLEMENTATION_PLAN.md Example .env file for configuring OAuth 2.1 authentication. Includes settings for both JWT and introspection validation methods. ```bash # Authorization Server Configuration OAUTH_AUTHORIZATION_SERVER=https://auth.example.com OAUTH_RESOURCE=https://mcp.example.com # JWT Validation OAUTH_JWKS_URI=https://auth.example.com/.well-known/jwks.json OAUTH_AUDIENCE=https://mcp.example.com OAUTH_ISSUER=https://auth.example.com # OR: Introspection Validation # OAUTH_INTROSPECTION_ENDPOINT=https://auth.example.com/oauth/introspect # OAUTH_CLIENT_ID=mcp-server # OAUTH_CLIENT_SECRET=your-client-secret ``` -------------------------------- ### Example: Making a Sampling Request Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/_autodocs/api-reference/MCPTool.md An example demonstrating how to use the samplingRequest method to query an LLM with specific messages and parameters, such as maxTokens. ```typescript const result = await this.samplingRequest({ messages: [{ role: "user", content: { type: "text", text: "Analyze this data" } }], maxTokens: 500 }); ``` -------------------------------- ### Basic DocsServer Initialization Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/docs/docs-package/server.md Initializes a DocsServer with a FumadocsRemoteSource. This is the fundamental setup for serving documentation via MCP. ```typescript import { DocsServer, FumadocsRemoteSource } from "@mcp-framework/docs"; const source = new FumadocsRemoteSource({ baseUrl: "https://docs.myapi.com", }); const server = new DocsServer({ source, name: "my-api-docs", version: "1.0.0", }); await server.start(); ``` -------------------------------- ### Configured Server Setup Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/_autodocs/QUICK_REFERENCE.md Set up an MCP server with custom configuration, including name, version, base path, logging, and transport options. ```typescript import { MCPServer } from "mcp-framework"; // With configuration const server = new MCPServer({ name: "my-server", version: "1.0.0", basePath: process.cwd(), logging: true, transport: { type: "sse", options: { port: 8080, endpoint: "/sse", messageEndpoint: "/messages" } } }); await server.start(); ``` -------------------------------- ### Static Resource Example Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/docs/resources.md Implement a static resource to serve fixed content, such as documentation. The `read` method returns predefined text content. ```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...", }, ]; } } ``` -------------------------------- ### Production HTTPS Setup (Behind Proxy) Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/docs/OAUTH.md Illustrates the recommended production setup for MCPServer, emphasizing the use of HTTPS, typically managed by an external proxy or load balancer. Avoids unencrypted HTTP for security. ```typescript // ❌ DO NOT use in production const server = new MCPServer({ transport: { type: "http-stream", options: { port: 8080, // Unencrypted HTTP auth: { /* OAuth config */ } } } }); // ✅ Production setup (behind HTTPS proxy/load balancer) // Use nginx, Caddy, or AWS ALB to terminate TLS ``` -------------------------------- ### Use Custom Source with DocsServer Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/docs/docs-package/custom-adapters.md Instantiate your custom `DocSource` and pass it to the `DocsServer` constructor. Then, start the server to serve your custom documentation. ```typescript import { DocsServer } from "@mcp-framework/docs"; const source = new MyCustomSource(); const server = new DocsServer({ source, name: "my-custom-docs", version: "1.0.0", }); server.start(); ``` -------------------------------- ### Project Structure Example Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/_autodocs/README.md Illustrates a typical directory layout for an MCP project, organizing tools, prompts, and resources. ```plaintext my-mcp-server/ ├── src/ │ ├── tools/ # Tool implementations │ │ ├── GetData.ts │ │ └── ProcessData.ts │ ├── prompts/ # Prompt implementations │ │ └── AnalyzePrompt.ts │ ├── resources/ # Resource implementations │ │ └── ConfigResource.ts │ └── index.ts # Server entry point ├── dist/ # Compiled JavaScript ├── package.json ├── tsconfig.json └── README.md ``` -------------------------------- ### Start the MCP Server Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/OAUTH_QUICK_START.md Initiate the MCP server to begin listening for connections and handling requests. ```typescript await server.start(); ``` -------------------------------- ### Example HTTP Request with Access Token Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/OAUTH_GUIDE.md Demonstrates how to include an access token in the Authorization header for API requests. ```http POST /messages?sessionId=xxx HTTP/1.1 Host: mcp.example.com Authorization: Bearer eyJhbGciOiJSUzI1NiIs... Content-Type: application/json { "jsonrpc": "2.0", "method": "tools/list", "id": 1 } ``` -------------------------------- ### Run Custom Token Validator Example Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/examples/README.md Builds and runs an advanced example demonstrating custom token validation using JWT and JWKS. This snippet is for scenarios requiring custom claims validation and advanced security features. ```bash npm run build node dist/examples/oauth-custom-validator.js ``` -------------------------------- ### Run MCP Server Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/README.md Start your MCP server using 'node dist/index.js'. The server validates tools upon startup before accepting connections. ```bash node dist/index.js # Server validates tools on startup ``` -------------------------------- ### API Key Authentication Example Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/_autodocs/api-reference/Authentication.md Demonstrates how to authenticate requests to the MCP API using an API Key. Ensure you replace 'your-api-key' with your actual key. ```shell curl -X POST http://localhost:8080/mcp \ -H "X-API-Key: your-api-key" \ -H "Content-Type: application/json" \ -d '{"jsonrpc": "2.0", "method": "tools/list", "id": 1}' ``` -------------------------------- ### Configure File-Based Logging Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/_autodocs/api-reference/MCPServer.md Enable file-based logging and set the log directory using environment variables when starting the application. ```bash MCP_ENABLE_FILE_LOGGING=true npm start ``` ```bash MCP_LOG_DIRECTORY=my-logs npm start ``` ```bash MCP_DEBUG_CONSOLE=true npm start ``` -------------------------------- ### API Key Authentication Setup Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/CHANGES.md Configure the MCPServer to use an API Key for authentication. Ensure the API_KEY environment variable is set. ```typescript import { MCPServer, APIKeyAuthProvider } from "mcp-framework"; const server = new MCPServer({ transport: { type: "sse", options: { auth: { provider: new APIKeyAuthProvider({ keys: [process.env.API_KEY] }) } } } }); ``` -------------------------------- ### Import MCP Framework Modules Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/OAUTH_QUICK_START.md Import the necessary classes from the mcp-framework library to get started. ```typescript import { MCPServer, OAuthProvider } from "mcp-framework"; ``` -------------------------------- ### Initialize DocsServer with FumadocsRemoteSource Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/docs/docs-package/overview.md Use this snippet to set up a documentation server that connects to a Fumadocs-based documentation site. Ensure you have the correct baseUrl for your documentation. ```typescript import { DocsServer, FumadocsRemoteSource } from "@mcp-framework/docs"; const source = new FumadocsRemoteSource({ baseUrl: "https://docs.myapi.com", }); const server = new DocsServer({ source, name: "my-api-docs", version: "1.0.0", }); server.start(); ``` -------------------------------- ### Example Implementation of read() Method Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/_autodocs/api-reference/MCPResource.md An example of how to implement the read() method to read content from a local JSON file. ```typescript async read() { const content = await fs.promises.readFile('./data.json', 'utf-8'); return [{ uri: this.uri, mimeType: 'application/json', text: content }]; } ``` -------------------------------- ### Scaffold and Run MCP Docs Server (CLI) Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/README.md Use the CLI to scaffold a new MCP documentation server project, configure the documentation site URL, and then build and run the server. ```bash # Scaffold a new docs MCP server project npx create-docs-mcp my-api-docs cd my-api-docs # Configure your docs site URL cp .env.example .env # Edit .env → set DOCS_BASE_URL=https://docs.myapi.com # Build and run npm run build npm start ``` -------------------------------- ### Client JWT Authentication Header Example Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/README.md Example of how a client should format the Authorization header with a Bearer token for JWT authentication. ```text Authorization: Bearer eyJhbGciOiJIUzI1NiIs... ``` -------------------------------- ### Composed AuthProvider Example Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/docs/docs-package/satp-agent-trust.md Example of a custom composed authentication provider that combines JWT authentication with SATPProvider for secondary trust verification. ```typescript // Your custom composed provider class ComposedProvider implements AuthProvider { private jwt = new JWTProvider(jwtConfig); private satp = new SATPProvider({ minTrustScore: 30 }); async authenticate(req: IncomingMessage) { const jwtResult = await this.jwt.authenticate(req); if (!jwtResult) return false; const satpResult = await this.satp.authenticate(req); return satpResult; // Trust data in result.data.agentTrust } } ``` -------------------------------- ### CLI Help for OAuth Project Creation Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/OAUTH_IMPLEMENTATION_PLAN.md Displays help information for the 'mcp create' command, including the --oauth flag for configuring OAuth 2.1 authentication. ```bash $ mcp create [options] Options: --http Use HTTP transport instead of default stdio --port Specify HTTP port (default: 8080) --cors Enable CORS with wildcard (*) access --oauth Configure OAuth 2.1 authentication -h, --help Display help for command Examples: $ mcp create my-server $ mcp create my-server --http --port 3000 $ mcp create my-server --http --oauth ``` -------------------------------- ### Create a new MCP Server Project Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/README.md Use the 'mcp create' command to initialize a new server project and navigate into its directory. ```bash mcp create my-mcp-server cd my-mcp-server ``` -------------------------------- ### Example Cognito DCR Output Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/examples/README-COGNITO.md This is an example of the output you will receive after successfully registering an OAuth client. Note the Client ID and Client Secret. ```text 📋 Client Credentials ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ Client ID: 1m3mpk6fioslohhl54the6ugoh Client Secret: prohg87lsuon3gnemk11ahkiu1kcnjsekghuesoideihh5m2dtu ``` -------------------------------- ### Create MCP Documentation Server Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/docs/docs-package/fumadocs-setup.md Use npx to create a new MCP documentation server project, navigate into its directory, and configure environment variables for the base URL and server name. ```bash npx create-docs-server my-api-docs cd my-api-docs # Edit .env: # DOCS_BASE_URL=https://docs.yoursite.com # DOCS_SERVER_NAME=my-api-docs npm run build npm start ``` -------------------------------- ### Create a New Docs Server Project Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/docs/docs-package/cli.md Use this command to scaffold a new documentation server project. It initializes a project structure with pre-configured files for an MCP server. ```bash npx create-docs-server my-api-docs ``` -------------------------------- ### Install Vite and Vite Single File Plugin Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/docs/apps.md Install the necessary Vite packages as development dependencies for bundling your MCP application into a single HTML file. ```bash npm install -D vite vite-plugin-singlefile ``` -------------------------------- ### Initialize MCPServer with Basic Configuration Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/_autodocs/configuration.md Use this snippet to initialize MCPServer with essential server settings and a stdio transport. ```typescript const server = new MCPServer({ name: "my-server", version: "1.0.0", basePath: "/path/to/project", transport: { type: "stdio" }, logging: true, tasks: { enabled: true } }); ``` -------------------------------- ### Install React Dependencies for MCP App Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/docs/apps.md Installs the necessary npm packages for a React-based MCP App, including the SDK, React, and Vite build tools. ```bash npm install @modelcontextprotocol/ext-apps @modelcontextprotocol/sdk react react-dom npm install -D @types/react @types/react-dom @vitejs/plugin-react vite vite-plugin-singlefile ``` -------------------------------- ### Basic MCP Server Setup with OAuth Provider Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/OAUTH_IMPLEMENTATION_SUMMARY.md Demonstrates how to configure an MCP Server with an SSE transport and an OAuthProvider for authentication. Ensure the OAuthProvider is correctly instantiated with authorization server details and client ID. ```typescript import { MCPServer, OAuthProvider } from "mcp-framework"; const server = new MCPServer({ transport: { type: "sse", options: { auth: { provider: new OAuthProvider({ authorizationServer: "https://auth.example.com", clientId: "your-client-id", resourceUri: "https://mcp.example.com", }) } } } }); ``` -------------------------------- ### Example: Reporting Progress in execute Method Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/_autodocs/api-reference/MCPTool.md An example demonstrating how to use the reportProgress method within the execute method to provide real-time feedback to the client during item processing. ```typescript async execute(input: MCPInput) { for (let i = 0; i < items.length; i++) { await this.reportProgress(i + 1, items.length, `Processing ${i + 1}/${items.length}`); await processItem(items[i]); } } ``` -------------------------------- ### Standalone MCPApp Example Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/docs/apps.md Define a standalone MCPApp subclass for complex UIs. This example shows how to configure UI resources, CSP, and define both LLM-accessible and app-only tools. ```typescript import { MCPApp } from "mcp-framework"; import { z } from "zod"; import { readFileSync } from "fs"; import { join, dirname } from "url"; import { fileURLToPath } from "url"; const __dirname = dirname(fileURLToPath(import.meta.url)); class DashboardApp extends MCPApp { name = "dashboard"; ui = { resourceUri: "ui://dashboard/view", resourceName: "Analytics Dashboard", resourceDescription: "Interactive analytics with charts and filters", csp: { connectDomains: ["https://api.analytics.com"], resourceDomains: ["https://cdn.jsdelivr.net"], }, prefersBorder: true, }; getContent() { return readFileSync( join(__dirname, "../../app-views/dashboard/index.html"), "utf-8" ); } tools = [ { name: "show_dashboard", description: "Display the analytics dashboard", schema: z.object({ timeRange: z.string().describe("Time range (e.g., '7d', '30d')"), metrics: z.array(z.string()).optional().describe("Metrics to display"), }), execute: async (input: { timeRange: string; metrics?: string[] }) => { const data = await fetchAnalytics(input.timeRange, input.metrics); return { data, summary: `Analytics for ${input.timeRange}` }; }, }, { // App-only tool: the UI can call this, but the LLM can't see it name: "refresh_data", description: "Refresh a specific metric", visibility: ["app"] as const, schema: z.object({ metric: z.string().describe("Metric to refresh"), }), execute: async (input: { metric: string }) => { return await fetchMetric(input.metric); }, }, ]; } export default DashboardApp; ``` -------------------------------- ### Example Validation Error Message Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/README.md An example of a tool validation error message indicating missing descriptions for Zod schema fields. It suggests using .describe() on each field. ```bash ❌ Tool validation failed: ❌ PriceFetcher.js: Missing descriptions for fields in price_fetcher: symbol, currency. All fields must have descriptions when using Zod object schemas. Use .describe() on each field, e.g., z.string().describe("Field description") ``` -------------------------------- ### Initialize MCP Docs Server Programmatically Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/README.md Programmatically initialize an MCP documentation server using `DocsServer` and a remote source adapter like `FumadocsRemoteSource`. ```typescript import { DocsServer, FumadocsRemoteSource } from "@mcpframework/docs"; const source = new FumadocsRemoteSource({ baseUrl: "https://docs.myapi.com", }); const server = new DocsServer({ source, name: "my-api-docs", version: "1.0.0", }); server.start(); ``` -------------------------------- ### Define Schema with Missing Description (Error Example) Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/_autodocs/api-reference/HelperFunctions.md This example demonstrates how defineSchema throws an error in development if a field is missing a description, highlighting the importance of using .describe(). ```typescript // This throws in development: // Error: Field 'email' is missing a description. // Use .describe() to add one. const badSchema = defineSchema({ email: z.string().email() // Missing .describe() }); ``` -------------------------------- ### JWT Validation Configuration Example Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/PERFORMANCE_REPORT.md Provides a TypeScript configuration example for JWT validation, specifying parameters like JWKS URI, audience, issuer, and caching options. ```typescript validation: { type: 'jwt', jwksUri: process.env.OAUTH_JWKS_URI, audience: process.env.OAUTH_AUDIENCE, issuer: process.env.OAUTH_ISSUER, cacheTTL: 900000, // 15 minutes cacheMaxEntries: 5 } ``` -------------------------------- ### Test OAuth Setup with Curl: Valid Token Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/docs/OAUTH.md Successfully access a protected resource by providing a valid authorization token. This confirms that your OAuth setup is working correctly. ```bash # 4. Try with valid token (should succeed) curl -v -X POST http://localhost:8080/mcp \ -H "Authorization: Bearer YOUR_VALID_TOKEN" \ -H "Content-Type: application/json" \ -d '{"jsonrpc": "2.0", "method": "tools/list", "id": 1}' ``` -------------------------------- ### Test OAuth Setup with Curl: Metadata Endpoint Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/docs/OAUTH.md Retrieve the OAuth metadata endpoint information using curl. This is often the first step in testing an OAuth setup. ```bash # 1. Get metadata endpoint curl http://localhost:8080/.well-known/oauth-protected-resource ``` -------------------------------- ### Zod Schema Validation Examples Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/_autodocs/QUICK_REFERENCE.md Provides examples of using Zod for schema validation, including constraints for strings and numbers, enums, arrays, objects, optional and nullable fields, defaults, unions, and the importance of `describe` for field descriptions. ```typescript // String with constraints z.string().min(1).max(100).email() z.string().url() z.string().uuid() z.string().regex(/pattern/) ``` ```typescript // Number constraints z.number().int().positive() z.number().min(0).max(100) ``` ```typescript // Enums z.enum(['a', 'b', 'c']) ``` ```typescript // Arrays z.array(z.string()) ``` ```typescript // Objects z.object({ field: z.string() }) ``` ```typescript // Optional z.string().optional() ``` ```typescript // Nullable z.string().nullable() ``` ```typescript // Default z.string().default('value') ``` ```typescript // Union z.union([z.string(), z.number()]) ``` ```typescript // All require descriptions z.string().describe("Field description") ``` -------------------------------- ### Scaffold a New Docs Project Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/packages/docs/README.md Instantly create a new MCP documentation project using npx. ```bash npx create-docs-mcp my-api-docs ``` -------------------------------- ### Run MCP Server with Cognito OAuth Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/examples/README-COGNITO.md Execute this command to start the MCP server with Cognito OAuth 2.1 integration. The output will show the server configuration and confirmation of successful startup. ```bash npx tsx examples/cognito-oauth-simple.ts ``` -------------------------------- ### MCPServer API Reference Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/_autodocs/DOCUMENTATION_COMPLETE.txt Documentation for MCPServer class, including server setup and related methods. ```APIDOC ## MCPServer ### Description Provides functionality for setting up and managing the MCP Server. ### Methods #### Server methods (4) - **start()**: Starts the MCP server. - **stop()**: Stops the MCP server. - **configure(config)**: Configures the MCP server with the provided configuration. - **getStatus()**: Retrieves the current status of the MCP server. ### Parameters #### configure(config) - **config** (MCPServerConfig) - Required - The server configuration object. ### Return Values - **start()**: Promise - **stop()**: Promise - **configure(config)**: void - **getStatus()**: ServerStatus ### Throws/Exceptions - `start()`: Throws an error if the server fails to start. - `stop()`: Throws an error if the server fails to stop. - `configure(config)`: Throws an error if the configuration is invalid. ### Usage Example ```javascript const server = new MCPServer(); await server.configure({ port: 8080 }); await server.start(); ``` ``` -------------------------------- ### Basic Task Creation and Management Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/_autodocs/api-reference/TaskManager.md Demonstrates how to create a TaskManager instance, create a new task, perform asynchronous work, and update its status, completion, or failure. ```typescript import { TaskManager } from 'mcp-framework'; class LongRunningTool extends MCPTool { private taskManager = new TaskManager({ defaultTtl: 600000, maxTasks: 50 }); async execute(input: MCPInput) { // Create a new task const task = this.taskManager.createTask(); // Perform long-running work asynchronously this.performLongWork(task.taskId).catch(error => { this.taskManager.failTask(task.taskId, error); }); // Return task ID immediately return { taskId: task.taskId, status: 'working', message: 'Processing started' }; } private async performLongWork(taskId: string) { try { // Update status this.taskManager.updateStatus(taskId, 'working', 'Processing data...'); // Simulate work const result = await this.heavyComputation(); // Complete the task this.taskManager.completeTask(taskId, result); } catch (error) { this.taskManager.failTask(taskId, error); } } } ``` -------------------------------- ### JWT Authentication Example Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/_autodocs/api-reference/Authentication.md Configure JWT authentication for your MCPServer. Ensure the JWT_SECRET environment variable is set. ```typescript import { MCPServer, JWTAuthProvider } from "mcp-framework"; const server = new MCPServer({ transport: { type: "sse", options: { port: 8080, auth: { provider: new JWTAuthProvider({ secret: process.env.JWT_SECRET, algorithms: ['HS256'], headerName: 'Authorization' }), endpoints: { sse: true, messages: true } } } } }); ``` -------------------------------- ### Tool Schema Definition Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/CLAUDE.md Example of defining a Zod schema for a tool, including mandatory descriptions for fields. ```typescript const schema = z.object({ message: z.string().describe("Message to process"), // Description is required count: z.number().optional().describe("Optional count") }); class MyTool extends MCPTool { name = "my_tool"; description = "Tool description"; schema = schema; async execute(input: MCPInput) { // input is fully typed from schema } } ``` -------------------------------- ### Client Receives 401 Unauthorized Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/OAUTH_QUICK_START.md Example HTTP response indicating that a request to /messages requires authorization. ```http GET /messages HTTP/1.1 HTTP/1.1 401 Unauthorized WWW-Authenticate: Bearer realm="MCP Server", resource="https://mcp.example.com", authorization_uri="https://auth.example.com" ``` -------------------------------- ### CLI Commands for Project Management Source: https://github.com/quantgeekdev/mcp-framework.git/blob/main/_autodocs/QUICK_REFERENCE.md Use these commands to create new projects, add components like tools, prompts, and resources, and validate your project. ```bash # Create new project mcp create my-server mcp create my-server --http --port 8080 # Add components mcp add tool calculator mcp add prompt analysis mcp add resource config # Validate tools mcp validate # Build with validation npm run build ```