diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 0000000..b17149b --- /dev/null +++ b/.prettierignore @@ -0,0 +1 @@ +*.mdx \ No newline at end of file diff --git a/README.md b/README.md index 4cbe075..6c10353 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,6 @@ -# Mintlify Starter Kit +# Model Context Protocol Documentation -Click on `Use this template` to copy the Mintlify starter kit. The starter kit contains examples including - -- Guide pages -- Navigation -- Customizations -- API Reference pages -- Use of popular components +The official docs of MCP. This README is a WIP. ### Development @@ -24,7 +18,7 @@ mintlify dev ### Publishing Changes -Install our Github App to auto propagate changes from your repo to your deployment. Changes will be deployed to production automatically after pushing to the default branch. Find the link to install on your dashboard. +Install our Github App to auto propagate changes from your repo to your deployment. Changes will be deployed to production automatically after pushing to the default branch. Find the link to install on your dashboard. #### Troubleshooting diff --git a/api-reference/client-api/connection-management.mdx b/api-reference/client-api/connection-management.mdx new file mode 100644 index 0000000..844f896 --- /dev/null +++ b/api-reference/client-api/connection-management.mdx @@ -0,0 +1,8 @@ +--- +title: "Connection Management" +description: "Manage MCP client connections" +--- + +# Connection Management + +Manage MCP client connections diff --git a/api-reference/client-api/resource-consumption.mdx b/api-reference/client-api/resource-consumption.mdx new file mode 100644 index 0000000..39388bf --- /dev/null +++ b/api-reference/client-api/resource-consumption.mdx @@ -0,0 +1,8 @@ +--- +title: "Resource Consumption" +description: "Work with MCP resources from clients" +--- + +# Resource Consumption + +Work with MCP resources from clients diff --git a/api-reference/client-api/tool-invocation.mdx b/api-reference/client-api/tool-invocation.mdx new file mode 100644 index 0000000..a76a659 --- /dev/null +++ b/api-reference/client-api/tool-invocation.mdx @@ -0,0 +1,8 @@ +--- +title: "Tool Invocation" +description: "Invoke MCP tools from clients" +--- + +# Tool Invocation + +Invoke MCP tools from clients diff --git a/api-reference/endpoint/create.mdx b/api-reference/endpoint/create.mdx deleted file mode 100644 index 5689f1b..0000000 --- a/api-reference/endpoint/create.mdx +++ /dev/null @@ -1,4 +0,0 @@ ---- -title: 'Create Plant' -openapi: 'POST /plants' ---- diff --git a/api-reference/endpoint/delete.mdx b/api-reference/endpoint/delete.mdx deleted file mode 100644 index 657dfc8..0000000 --- a/api-reference/endpoint/delete.mdx +++ /dev/null @@ -1,4 +0,0 @@ ---- -title: 'Delete Plant' -openapi: 'DELETE /plants/{id}' ---- diff --git a/api-reference/endpoint/get.mdx b/api-reference/endpoint/get.mdx deleted file mode 100644 index 56aa09e..0000000 --- a/api-reference/endpoint/get.mdx +++ /dev/null @@ -1,4 +0,0 @@ ---- -title: 'Get Plants' -openapi: 'GET /plants' ---- diff --git a/api-reference/error-handling.mdx b/api-reference/error-handling.mdx new file mode 100644 index 0000000..b5932b7 --- /dev/null +++ b/api-reference/error-handling.mdx @@ -0,0 +1,8 @@ +--- +title: "Error Handling" +description: "Handle errors in MCP implementations" +--- + +# Error Handling + +Handle errors in MCP implementations diff --git a/api-reference/introduction.mdx b/api-reference/introduction.mdx deleted file mode 100644 index c835b78..0000000 --- a/api-reference/introduction.mdx +++ /dev/null @@ -1,33 +0,0 @@ ---- -title: 'Introduction' -description: 'Example section for showcasing API endpoints' ---- - - - If you're not looking to build API reference documentation, you can delete - this section by removing the api-reference folder. - - -## Welcome - -There are two ways to build API documentation: [OpenAPI](https://mintlify.com/docs/api-playground/openapi/setup) and [MDX components](https://mintlify.com/docs/api-playground/mdx/configuration). For the starter kit, we are using the following OpenAPI specification. - - - View the OpenAPI specification file - - -## Authentication - -All API endpoints are authenticated using Bearer tokens and picked up from the specification file. - -```json -"security": [ - { - "bearerAuth": [] - } -] -``` diff --git a/api-reference/message-types.mdx b/api-reference/message-types.mdx new file mode 100644 index 0000000..fe9cff8 --- /dev/null +++ b/api-reference/message-types.mdx @@ -0,0 +1,8 @@ +--- +title: "Message Types" +description: "Complete reference of MCP message formats" +--- + +# Message Types + +Complete reference of MCP message formats diff --git a/api-reference/openapi.json b/api-reference/openapi.json deleted file mode 100644 index b1509be..0000000 --- a/api-reference/openapi.json +++ /dev/null @@ -1,195 +0,0 @@ -{ - "openapi": "3.0.1", - "info": { - "title": "OpenAPI Plant Store", - "description": "A sample API that uses a plant store as an example to demonstrate features in the OpenAPI specification", - "license": { - "name": "MIT" - }, - "version": "1.0.0" - }, - "servers": [ - { - "url": "http://sandbox.mintlify.com" - } - ], - "security": [ - { - "bearerAuth": [] - } - ], - "paths": { - "/plants": { - "get": { - "description": "Returns all plants from the system that the user has access to", - "parameters": [ - { - "name": "limit", - "in": "query", - "description": "The maximum number of results to return", - "schema": { - "type": "integer", - "format": "int32" - } - } - ], - "responses": { - "200": { - "description": "Plant response", - "content": { - "application/json": { - "schema": { - "type": "array", - "items": { - "$ref": "#/components/schemas/Plant" - } - } - } - } - }, - "400": { - "description": "Unexpected error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/Error" - } - } - } - } - } - }, - "post": { - "description": "Creates a new plant in the store", - "requestBody": { - "description": "Plant to add to the store", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/NewPlant" - } - } - }, - "required": true - }, - "responses": { - "200": { - "description": "plant response", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/Plant" - } - } - } - }, - "400": { - "description": "unexpected error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/Error" - } - } - } - } - } - } - }, - "/plants/{id}": { - "delete": { - "description": "Deletes a single plant based on the ID supplied", - "parameters": [ - { - "name": "id", - "in": "path", - "description": "ID of plant to delete", - "required": true, - "schema": { - "type": "integer", - "format": "int64" - } - } - ], - "responses": { - "204": { - "description": "Plant deleted", - "content": {} - }, - "400": { - "description": "unexpected error", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/Error" - } - } - } - } - } - } - } - }, - "components": { - "schemas": { - "Plant": { - "required": [ - "name" - ], - "type": "object", - "properties": { - "name": { - "description": "The name of the plant", - "type": "string" - }, - "tag": { - "description": "Tag to specify the type", - "type": "string" - } - } - }, - "NewPlant": { - "allOf": [ - { - "$ref": "#/components/schemas/Plant" - }, - { - "required": [ - "id" - ], - "type": "object", - "properties": { - "id": { - "description": "Identification number of the plant", - "type": "integer", - "format": "int64" - } - } - } - ] - }, - "Error": { - "required": [ - "error", - "message" - ], - "type": "object", - "properties": { - "error": { - "type": "integer", - "format": "int32" - }, - "message": { - "type": "string" - } - } - } - }, - "securitySchemes": { - "bearerAuth": { - "type": "http", - "scheme": "bearer" - } - } - } -} \ No newline at end of file diff --git a/api-reference/protocol-overview.mdx b/api-reference/protocol-overview.mdx new file mode 100644 index 0000000..b58d90a --- /dev/null +++ b/api-reference/protocol-overview.mdx @@ -0,0 +1,8 @@ +--- +title: "Protocol Overview" +description: "Understanding the Model Context Protocol" +--- + +# Protocol Overview + +Understanding the Model Context Protocol diff --git a/api-reference/python/class-reference.mdx b/api-reference/python/class-reference.mdx new file mode 100644 index 0000000..43739a4 --- /dev/null +++ b/api-reference/python/class-reference.mdx @@ -0,0 +1,8 @@ +--- +title: "Python Class Reference" +description: "Complete Python SDK class documentation" +--- + +# Python Class Reference + +Complete Python SDK class documentation diff --git a/api-reference/python/examples.mdx b/api-reference/python/examples.mdx new file mode 100644 index 0000000..94c751c --- /dev/null +++ b/api-reference/python/examples.mdx @@ -0,0 +1,8 @@ +--- +title: "Python Examples" +description: "Example Python implementations" +--- + +# Python Examples + +Example Python implementations diff --git a/api-reference/python/type-hints.mdx b/api-reference/python/type-hints.mdx new file mode 100644 index 0000000..d037e47 --- /dev/null +++ b/api-reference/python/type-hints.mdx @@ -0,0 +1,8 @@ +--- +title: "Python Type Hints" +description: "Python type system documentation" +--- + +# Python Type Hints + +Python type system documentation diff --git a/api-reference/server-api/event-handling.mdx b/api-reference/server-api/event-handling.mdx new file mode 100644 index 0000000..dab1bc3 --- /dev/null +++ b/api-reference/server-api/event-handling.mdx @@ -0,0 +1,8 @@ +--- +title: "Event Handling" +description: "Handle events in your MCP server" +--- + +# Event Handling + +Handle events in your MCP server diff --git a/api-reference/server-api/resource-management.mdx b/api-reference/server-api/resource-management.mdx new file mode 100644 index 0000000..34de1ab --- /dev/null +++ b/api-reference/server-api/resource-management.mdx @@ -0,0 +1,8 @@ +--- +title: "Resource Management" +description: "Manage resources in your MCP server" +--- + +# Resource Management + +Manage resources in your MCP server diff --git a/api-reference/server-api/tool-implementation.mdx b/api-reference/server-api/tool-implementation.mdx new file mode 100644 index 0000000..0ede2a0 --- /dev/null +++ b/api-reference/server-api/tool-implementation.mdx @@ -0,0 +1,8 @@ +--- +title: "Tool Implementation" +description: "Implement tools in your MCP server" +--- + +# Tool Implementation + +Implement tools in your MCP server diff --git a/api-reference/typescript/class-reference.mdx b/api-reference/typescript/class-reference.mdx new file mode 100644 index 0000000..c08a40d --- /dev/null +++ b/api-reference/typescript/class-reference.mdx @@ -0,0 +1,8 @@ +--- +title: "TypeScript Class Reference" +description: "Complete TypeScript SDK class documentation" +--- + +# TypeScript Class Reference + +Complete TypeScript SDK class documentation diff --git a/api-reference/typescript/examples.mdx b/api-reference/typescript/examples.mdx new file mode 100644 index 0000000..7b5b7b5 --- /dev/null +++ b/api-reference/typescript/examples.mdx @@ -0,0 +1,8 @@ +--- +title: "TypeScript Examples" +description: "Example TypeScript implementations" +--- + +# TypeScript Examples + +Example TypeScript implementations diff --git a/api-reference/typescript/type-definitions.mdx b/api-reference/typescript/type-definitions.mdx new file mode 100644 index 0000000..cebeb24 --- /dev/null +++ b/api-reference/typescript/type-definitions.mdx @@ -0,0 +1,8 @@ +--- +title: "TypeScript Type Definitions" +description: "TypeScript type system documentation" +--- + +# TypeScript Type Definitions + +TypeScript type system documentation diff --git a/development.mdx b/development.mdx deleted file mode 100644 index c2f2ccd..0000000 --- a/development.mdx +++ /dev/null @@ -1,106 +0,0 @@ ---- -title: 'Development' -description: 'Preview changes locally to update your docs' ---- - - - **Prerequisite**: Please install Node.js (version 19 or higher) before proceeding. - - -Follow these steps to install and run Mintlify on your operating system: - -**Step 1**: Install Mintlify: - - - - ```bash npm - npm i -g mintlify - ``` - -```bash yarn -yarn global add mintlify -``` - - - -**Step 2**: Navigate to the docs directory (where the `mint.json` file is located) and execute the following command: - -```bash -mintlify dev -``` - -A local preview of your documentation will be available at `http://localhost:3000`. - -### Custom Ports - -By default, Mintlify uses port 3000. You can customize the port Mintlify runs on by using the `--port` flag. To run Mintlify on port 3333, for instance, use this command: - -```bash -mintlify dev --port 3333 -``` - -If you attempt to run Mintlify on a port that's already in use, it will use the next available port: - -```md -Port 3000 is already in use. Trying 3001 instead. -``` - -## Mintlify Versions - -Please note that each CLI release is associated with a specific version of Mintlify. If your local website doesn't align with the production version, please update the CLI: - - - -```bash npm -npm i -g mintlify@latest -``` - -```bash yarn -yarn global upgrade mintlify -``` - - - -## Validating Links - -The CLI can assist with validating reference links made in your documentation. To identify any broken links, use the following command: - -```bash -mintlify broken-links -``` - -## Deployment - - - Unlimited editors available under the [Pro - Plan](https://mintlify.com/pricing) and above. - - -If the deployment is successful, you should see the following: - - - - - -## Code Formatting - -We suggest using extensions on your IDE to recognize and format MDX. If you're a VSCode user, consider the [MDX VSCode extension](https://marketplace.visualstudio.com/items?itemName=unifiedjs.vscode-mdx) for syntax highlighting, and [Prettier](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode) for code formatting. - -## Troubleshooting - - - - - This may be due to an outdated version of node. Try the following: - 1. Remove the currently-installed version of mintlify: `npm remove -g mintlify` - 2. Upgrade to Node v19 or higher. - 3. Reinstall mintlify: `npm install -g mintlify` - - - - - Solution: Go to the root of your device and delete the \~/.mintlify folder. Afterwards, run `mintlify dev` again. - - - -Curious about what changed in the CLI version? [Check out the CLI changelog.](https://www.npmjs.com/package/mintlify?activeTab=versions) diff --git a/docs/core/architecture.mdx b/docs/core/architecture.mdx new file mode 100644 index 0000000..c987d90 --- /dev/null +++ b/docs/core/architecture.mdx @@ -0,0 +1,282 @@ +--- +title: "Core Architecture" +description: "Understand how MCP connects clients, servers, and LLMs" +--- + +The Model Context Protocol (MCP) is built on a flexible, extensible architecture that enables seamless communication between LLM applications and external services. This document covers the core architectural components and concepts. + +## Overview + +MCP follows a client-server architecture where: + +- **Clients** are LLM applications (like claude.ai or IDEs) that initiate connections +- **Servers** provide context, tools, and prompts to clients +- **Hosts** are processes that run MCP clients + +```mermaid +flowchart LR + subgraph "Host (e.g., claude.ai)" + client[MCP Client] + end + subgraph "Server Process" + server[MCP Server] + end + + client <-->|Transport Layer| server +``` + +## Core components + +### Protocol Layer + +The protocol layer handles message framing, request/response linking, and high-level communication patterns. Key classes include: + +```typescript +class Protocol { + // Handle incoming requests + setRequestHandler(schema: T, handler: (request: T) => Result): void + + // Handle incoming notifications + setNotificationHandler(schema: T, handler: (notification: T) => void): void + + // Send requests and await responses + request(request: Request, schema: T): Promise + + // Send one-way notifications + notification(notification: Notification): Promise +} +``` + +### Transport layer + +The transport layer handles the actual communication between clients and servers. MCP supports multiple transport mechanisms: + +1. **stdio Transport** + - Uses standard input/output for communication + - Ideal for local processes + ```typescript + class StdioTransport implements Transport { + constructor(stdin: Readable, stdout: Writable) + send(message: JSONRPCMessage): Promise + } + ``` + +2. **WebSocket Transport** + - Enables real-time bidirectional communication + - Supports remote connections + ```typescript + class WebSocketTransport implements Transport { + constructor(url: URL) + send(message: JSONRPCMessage): Promise + } + ``` + +3. **SSE Transport** + - Uses Server-Sent Events for server-to-client messages + - HTTP POST for client-to-server messages + ```typescript + class SSETransport implements Transport { + constructor(url: URL) + send(message: JSONRPCMessage): Promise + } + ``` + +### Message types + +MCP uses JSON-RPC 2.0 as its message format with three main types: + +1. **Requests** + ```typescript + interface Request { + method: string + params?: { + _meta?: { + progressToken?: string | number + } + } + } + ``` + +2. **Notifications** + ```typescript + interface Notification { + method: string + params?: { + _meta?: Record + } + } + ``` + +3. **Results** + ```typescript + interface Result { + _meta?: Record + [key: string]: unknown + } + ``` + +## Connection lifecycle + +### 1. Initialization + +```mermaid +sequenceDiagram + participant Client + participant Server + + Client->>Server: initialize request + Server->>Client: initialize response + Client->>Server: initialized notification + + Note over Client,Server: Connection ready for use +``` + +1. Client sends `initialize` request with capabilities +2. Server responds with supported features +3. Client sends `initialized` notification +4. Normal message exchange begins + +### 2. Message Exchange + +After initialization, the following patterns are supported: + +- **Request-Response**: Client sends request, server responds +- **Notifications**: Either party sends one-way messages +- **Progress Updates**: Long-running operations can report progress +- **Resource Updates**: Servers notify about changed resources + +### 3. Termination + +Either party can terminate the connection: +- Clean shutdown via `close()` +- Transport disconnection +- Error conditions + +## Error handling + +MCP defines standard error codes and handling: + +```typescript +enum ErrorCode { + ConnectionClosed = -1, + ParseError = -32700, + InvalidRequest = -32600, + MethodNotFound = -32601, + InvalidParams = -32602, + InternalError = -32603 +} +``` + +Errors are propagated through: +- Error responses to requests +- Error events on transports +- Protocol-level error handlers + +## Implementation example + +Here's a basic example of implementing an MCP server: + +```typescript +import { Server } from "@modelcontextprotocol/sdk/server"; +import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio"; + +const server = new Server({ + name: "example-server", + version: "1.0.0" +}); + +// Handle requests +server.setRequestHandler(ListResourcesRequestSchema, async () => { + return { + resources: [ + { + uri: "example://resource", + name: "Example Resource" + } + ] + }; +}); + +// Connect transport +const transport = new StdioServerTransport(); +await server.connect(transport); +``` + +## Best practices + +### Transport selection + +1. **Local Communication** + - Use stdio transport for local processes + - Efficient for same-machine communication + - Simple process management + +2. **Remote Communication** + - WebSocket for full-duplex communication + - SSE for scenarios requiring HTTP compatibility + - Consider security implications + +### Message Handling + +1. **Request Processing** + - Validate inputs thoroughly + - Use type-safe schemas + - Handle errors gracefully + - Implement timeouts + +2. **Progress Reporting** + - Use progress tokens for long operations + - Report progress incrementally + - Include total progress when known + +3. **Error Management** + - Use appropriate error codes + - Include helpful error messages + - Clean up resources on errors + +## Security considerations + +1. **Transport Security** + - Use TLS for remote connections + - Validate connection origins + - Implement authentication when needed + +2. **Message Validation** + - Validate all incoming messages + - Sanitize inputs + - Check message size limits + - Verify JSON-RPC format + +3. **Resource Protection** + - Implement access controls + - Validate resource paths + - Monitor resource usage + - Rate limit requests + +4. **Error Handling** + - Don't leak sensitive information + - Log security-relevant errors + - Implement proper cleanup + - Handle DoS scenarios + +## Debugging and monitoring + +1. **Logging** + - Log protocol events + - Track message flow + - Monitor performance + - Record errors + +2. **Diagnostics** + - Implement health checks + - Monitor connection state + - Track resource usage + - Profile performance + +3. **Testing** + - Test different transports + - Verify error handling + - Check edge cases + - Load test servers + +This architecture provides a robust foundation for building MCP integrations while maintaining flexibility for different use cases and deployment scenarios. \ No newline at end of file diff --git a/docs/core/prompts.mdx b/docs/core/prompts.mdx new file mode 100644 index 0000000..d553287 --- /dev/null +++ b/docs/core/prompts.mdx @@ -0,0 +1,393 @@ +--- +title: "Prompts" +description: "Create resuable prompt templates and workflows" +--- + +MCP Prompts enable servers to define reusable prompt templates and workflows that clients can easily surface to users and LLMs. They provide a powerful way to standardize and share common LLM interactions. + +## Overview + +Prompts in MCP are predefined templates that can: +- Accept dynamic arguments +- Include context from resources +- Chain multiple interactions +- Guide specific workflows +- Surface as UI elements (like slash commands) + +## Prompt structure + +Each prompt is defined with: + +```typescript +{ + name: string; // Unique identifier for the prompt + description?: string; // Human-readable description + arguments?: [ // Optional list of arguments + { + name: string; // Argument identifier + description?: string; // Argument description + required?: boolean; // Whether argument is required + } + ] +} +``` + +## Discovering prompts + +Clients can discover available prompts through the `prompts/list` endpoint: + +```typescript +// Request +{ + method: "prompts/list" +} + +// Response +{ + prompts: [ + { + name: "analyze-code", + description: "Analyze code for potential improvements", + arguments: [ + { + name: "language", + description: "Programming language", + required: true + } + ] + } + ] +} +``` + +## Using prompts + +To use a prompt, clients make a `prompts/get` request: + +```typescript +// Request +{ + method: "prompts/get", + params: { + name: "analyze-code", + arguments: { + language: "python" + } + } +} + +// Response +{ + description?: string, // Optional context about the prompt + messages: [ // Messages to send to the LLM + { + role: "user" | "assistant", + content: { + type: "text" | "image", + text?: string, + data?: string, // base64 for images + mimeType?: string + } + } + ] +} +``` + +## Dynamic prompts + +Prompts can be dynamic and include: + +### Context Integration + +```typescript +const analyzeLogsPrompt = { + name: "analyze-logs", + description: "Analyze recent system logs", + arguments: [ + { + name: "timeframe", + description: "Time period to analyze", + required: true + } + ] +}; + +server.setRequestHandler(GetPromptRequestSchema, async (request) => { + if (request.params.name === "analyze-logs") { + const logs = await getSystemLogs(request.params.arguments?.timeframe); + return { + messages: [ + { + role: "user", + content: { + type: "text", + text: `Analyze these system logs and identify any issues:\n\n${logs}` + } + } + ] + }; + } +}); +``` + +### Resource references + +```typescript +const codeReviewPrompt = { + name: "review-code", + async getMessages(fileUri: string) { + const code = await readResource(fileUri); + return [ + { + role: "user", + content: { + type: "text", + text: `Review this code for best practices:\n\n${code}` + } + } + ]; + } +}; +``` + +### Multi-step workflows + +```typescript +const debugWorkflow = { + name: "debug-error", + async getMessages(error: string) { + return [ + { + role: "user", + content: { + type: "text", + text: "Here's an error I'm seeing:" + } + }, + { + role: "assistant", + content: { + type: "text", + text: "I'll help analyze this error. What have you tried so far?" + } + }, + { + role: "user", + content: { + type: "text", + text: error + } + } + ]; + } +}; +``` + +## Example implementation + +Here's a complete example of implementing prompts in an MCP server: + +```typescript +import { Server } from "@modelcontextprotocol/sdk/server"; +import { + ListPromptsRequestSchema, + GetPromptRequestSchema +} from "@modelcontextprotocol/sdk/types"; + +const PROMPTS = { + "git-commit": { + name: "git-commit", + description: "Generate a Git commit message", + arguments: [ + { + name: "changes", + description: "Git diff or description of changes", + required: true + } + ] + }, + "explain-code": { + name: "explain-code", + description: "Explain how code works", + arguments: [ + { + name: "code", + description: "Code to explain", + required: true + }, + { + name: "language", + description: "Programming language", + required: false + } + ] + } +}; + +const server = new Server({ + name: "example-prompts-server", + version: "1.0.0" +}); + +// List available prompts +server.setRequestHandler(ListPromptsRequestSchema, async () => { + return { + prompts: Object.values(PROMPTS) + }; +}); + +// Get specific prompt +server.setRequestHandler(GetPromptRequestSchema, async (request) => { + const prompt = PROMPTS[request.params.name]; + if (!prompt) { + throw new Error(`Prompt not found: ${request.params.name}`); + } + + if (request.params.name === "git-commit") { + return { + messages: [ + { + role: "user", + content: { + type: "text", + text: `Generate a concise but descriptive commit message for these changes:\n\n${request.params.arguments?.changes}` + } + } + ] + }; + } + + if (request.params.name === "explain-code") { + const language = request.params.arguments?.language || "Unknown"; + return { + messages: [ + { + role: "user", + content: { + type: "text", + text: `Explain how this ${language} code works:\n\n${request.params.arguments?.code}` + } + } + ] + }; + } + + throw new Error("Prompt implementation not found"); +}); +``` + +## Best practices + +When implementing prompts: + +1. Use clear, descriptive prompt names +2. Provide detailed descriptions for prompts and arguments +3. Validate all required arguments +4. Handle missing arguments gracefully +5. Consider versioning for prompt templates +6. Cache dynamic content when appropriate +7. Implement error handling +8. Document expected argument formats +9. Consider prompt composability +10. Test prompts with various inputs + +## UI integration + +Prompts can be surfaced in client UIs as: + +- Slash commands +- Quick actions +- Context menu items +- Command palette entries +- Guided workflows +- Interactive forms + +## Updates and changes + +Servers can notify clients about prompt changes: + +1. Server capability: `prompts.listChanged` +2. Notification: `notifications/prompts/list_changed` +3. Client re-fetches prompt list + +## Security considerations + +When implementing prompts: + +- Validate all arguments +- Sanitize user input +- Consider rate limiting +- Implement access controls +- Audit prompt usage +- Handle sensitive data appropriately +- Validate generated content +- Implement timeouts +- Consider prompt injection risks +- Document security requirements + +## Advanced features + +### Prompt chaining + +```typescript +const analyzePRPrompt = { + async getMessages(prId: string) { + // Chain multiple prompts + const diffPrompt = await getPrompt("analyze-diff"); + const testsPrompt = await getPrompt("review-tests"); + const securityPrompt = await getPrompt("security-review"); + + return [ + ...diffPrompt.messages, + ...testsPrompt.messages, + ...securityPrompt.messages + ]; + } +}; +``` + +### Context enrichment + +```typescript +const troubleshootPrompt = { + async getMessages(error: string) { + // Enrich with system context + const systemInfo = await getSystemInfo(); + const recentLogs = await getRecentLogs(); + const stackTrace = await parseError(error); + + return [ + { + role: "user", + content: { + type: "text", + text: `Help troubleshoot this error: +Error: ${error} +System: ${systemInfo} +Logs: ${recentLogs} +Stack: ${stackTrace}` + } + } + ]; + } +}; +``` + +### Interactive workflows + +```typescript +const debugWorkflow = { + async getMessages(stage: string, context: any) { + switch (stage) { + case "initial": + return promptForError(); + case "analysis": + return analyzeError(context.error); + case "solution": + return suggestFixes(context.analysis); + case "verification": + return verifyFix(context.solution); + } + } +}; +``` \ No newline at end of file diff --git a/docs/core/resources.mdx b/docs/core/resources.mdx new file mode 100644 index 0000000..517d629 --- /dev/null +++ b/docs/core/resources.mdx @@ -0,0 +1,197 @@ +--- +title: "Resources" +description: "Expose data and content from your servers to LLMs" +--- + +Resources are a core primitive in the Model Context Protocol (MCP) that allow servers to expose data and content that can be read by clients and used as context for LLM interactions. + +## Overview + +Resources represent any kind of data that an MCP server wants to make available to clients. This can include: + +- File contents +- Database records +- API responses +- Live system data +- Screenshots and images +- Log files +- And more + +Each resource is identified by a unique URI and can contain either text or binary data. + +## Resource URIs + +Resources are identified using URIs that follow this format: + +``` +[protocol]://[path] +``` + +For example: +- `file:///home/user/documents/report.pdf` +- `postgres://database/customers/schema` +- `screen://localhost/display1` + +The protocol and path structure is defined by the MCP server implementation. Servers can define their own custom URI schemes. + +## Resource types + +Resources can contain two types of content: + +### Text Resources + +Text resources contain UTF-8 encoded text data. These are suitable for: +- Source code +- Configuration files +- Log files +- JSON/XML data +- Plain text + +### Binary resources + +Binary resources contain raw binary data encoded in base64. These are suitable for: +- Images +- PDFs +- Audio files +- Video files +- Other non-text formats + +## Resource discovery + +Clients can discover available resources through two main methods: + +### Direct resources + +Servers expose a list of concrete resources via the `resources/list` endpoint. Each resource includes: + +```typescript +{ + uri: string; // Unique identifier for the resource + name: string; // Human-readable name + description?: string; // Optional description + mimeType?: string; // Optional MIME type +} +``` + +### Resource templates + +For dynamic resources, servers can expose URI templates that clients can use to construct valid resource URIs: + +```typescript +{ + uriTemplate: string; // URI template following RFC 6570 + name: string; // Human-readable name for this type + description?: string; // Optional description + mimeType?: string; // Optional MIME type for all matching resources +} +``` + +## Reading resources + +To read a resource, clients make a `resources/read` request with the resource URI. The server responds with: + +```typescript +{ + contents: [ + { + uri: string; // The requested URI + mimeType?: string; // Optional MIME type + + // One of: + text?: string; // For text resources + blob?: string; // For binary resources (base64 encoded) + } + ] +} +``` + +## Resource updates + +MCP supports real-time updates for resources through two mechanisms: + +### List changes + +Servers can notify clients when their list of available resources changes via the `notifications/resources/list_changed` notification. + +### Content changes + +Clients can subscribe to updates for specific resources: + +1. Client sends `resources/subscribe` with resource URI +2. Server sends `notifications/resources/updated` when the resource changes +3. Client can fetch latest content with `resources/read` +4. Client can unsubscribe with `resources/unsubscribe` + +## Example implementation + +Here's a simple example of implementing resource support in an MCP server: + +```typescript +const server = new Server({ + name: "example-server", + version: "1.0.0" +}); + +// List available resources +server.setRequestHandler(ListResourcesRequestSchema, async () => { + return { + resources: [ + { + uri: "file:///logs/app.log", + name: "Application Logs", + mimeType: "text/plain" + } + ] + }; +}); + +// Read resource contents +server.setRequestHandler(ReadResourceRequestSchema, async (request) => { + const uri = request.params.uri; + + if (uri === "file:///logs/app.log") { + const logContents = await readLogFile(); + return { + contents: [ + { + uri, + mimeType: "text/plain", + text: logContents + } + ] + }; + } + + throw new Error("Resource not found"); +}); +``` + +## Best practices + +When implementing resource support: + +1. Use clear, descriptive resource names and URIs +2. Include helpful descriptions to guide LLM understanding +3. Set appropriate MIME types when known +4. Implement resource templates for dynamic content +5. Use subscriptions for frequently changing resources +6. Handle errors gracefully with clear error messages +7. Consider pagination for large resource lists +8. Cache resource contents when appropriate +9. Validate URIs before processing +10. Document your custom URI schemes + +## Security considerations + +When exposing resources: + +- Validate all resource URIs +- Implement appropriate access controls +- Sanitize file paths to prevent directory traversal +- Be cautious with binary data handling +- Consider rate limiting for resource reads +- Audit resource access +- Encrypt sensitive data in transit +- Validate MIME types +- Implement timeouts for long-running reads +- Handle resource cleanup appropriately \ No newline at end of file diff --git a/docs/core/sampling.mdx b/docs/core/sampling.mdx new file mode 100644 index 0000000..21f9dbd --- /dev/null +++ b/docs/core/sampling.mdx @@ -0,0 +1,221 @@ +--- +title: "Sampling" +description: "Let your servers request completions from LLMs" +--- + +Sampling is a powerful MCP feature that allows servers to request LLM completions through the client, enabling sophisticated agentic behaviors while maintaining security and privacy. + +## How sampling works + +The sampling flow follows these steps: + +1. Server sends a `sampling/createMessage` request to the client +2. Client reviews the request and can modify it +3. Client samples from an LLM +4. Client reviews the completion +5. Client returns the result to the server + +This human-in-the-loop design ensures users maintain control over what the LLM sees and generates. + +## Message format + +Sampling requests use a standardized message format: + +```typescript +{ + messages: [ + { + role: "user" | "assistant", + content: { + type: "text" | "image", + // For text: + text?: string, + // For images: + data?: string, // base64 encoded + mimeType?: string + } + } + ], + systemPrompt?: string, + includeContext?: "none" | "thisServer" | "allServers", + temperature?: number, + maxTokens: number, + stopSequences?: string[], + metadata?: Record +} +``` + +## Request parameters + +### Messages + +The `messages` array contains the conversation history to send to the LLM. Each message has: + +- `role`: Either "user" or "assistant" +- `content`: The message content, which can be: + - Text content with a `text` field + - Image content with `data` (base64) and `mimeType` fields + +### System prompt + +An optional `systemPrompt` field allows servers to request a specific system prompt. The client may modify or ignore this. + +### Context inclusion + +The `includeContext` parameter specifies what MCP context to include: + +- `"none"`: No additional context +- `"thisServer"`: Include context from the requesting server +- `"allServers"`: Include context from all connected MCP servers + +The client controls what context is actually included. + +### Sampling parameters + +Fine-tune the LLM sampling with: + +- `temperature`: Controls randomness (0.0 to 1.0) +- `maxTokens`: Maximum tokens to generate +- `stopSequences`: Array of sequences that stop generation +- `metadata`: Additional provider-specific parameters + +## Response format + +The client returns a completion result: + +```typescript +{ + model: string, // Name of the model used + stopReason: "endTurn" | "stopSequence" | "maxTokens", + role: "user" | "assistant", + content: { + type: "text" | "image", + text?: string, + data?: string, + mimeType?: string + } +} +``` + +## Example implementation + +Here's an example of requesting sampling from a client: + +```typescript +// Server-side code +const response = await server.request({ + method: "sampling/createMessage", + params: { + messages: [ + { + role: "user", + content: { + type: "text", + text: "What files are in the current directory?" + } + } + ], + systemPrompt: "You are a helpful file system assistant.", + includeContext: "thisServer", + maxTokens: 100, + temperature: 0.7 + } +}, CreateMessageResultSchema); + +// Handle the completion +console.log(response.content.text); +``` + +## Best practices + +When implementing sampling: + +1. Always provide clear, well-structured prompts +2. Handle both text and image content appropriately +3. Set reasonable token limits +4. Include relevant context through `includeContext` +5. Validate responses before using them +6. Handle errors gracefully +7. Consider rate limiting sampling requests +8. Document expected sampling behavior +9. Test with various model parameters +10. Monitor sampling costs + +## Human-in-the-loop controls + +Sampling is designed with human oversight in mind: + +### For prompts + +- Clients should show users the proposed prompt +- Users should be able to modify or reject prompts +- System prompts can be filtered or modified +- Context inclusion is controlled by the client + +### For completions + +- Clients should show users the completion +- Users should be able to modify or reject completions +- Clients can filter or modify completions +- Users control which model is used + +## Security considerations + +When implementing sampling: + +- Validate all message content +- Sanitize sensitive information +- Implement appropriate rate limits +- Monitor sampling usage +- Encrypt data in transit +- Handle user data privacy +- Audit sampling requests +- Control cost exposure +- Implement timeouts +- Handle model errors gracefully + +## Common patterns + +### Agentic workflows + +Sampling enables agentic patterns like: + +- Reading and analyzing resources +- Making decisions based on context +- Generating structured data +- Handling multi-step tasks +- Providing interactive assistance + +### Context management + +Best practices for context: + +- Request minimal necessary context +- Structure context clearly +- Handle context size limits +- Update context as needed +- Clean up stale context + +### Error handling + +Robust error handling should: + +- Catch sampling failures +- Handle timeout errors +- Manage rate limits +- Validate responses +- Provide fallback behaviors +- Log errors appropriately + +## Limitations + +Be aware of these limitations: + +- Sampling depends on client capabilities +- Users control sampling behavior +- Context size has limits +- Rate limits may apply +- Costs should be considered +- Model availability varies +- Response times vary +- Not all content types supported \ No newline at end of file diff --git a/docs/core/tools.mdx b/docs/core/tools.mdx new file mode 100644 index 0000000..2697e84 --- /dev/null +++ b/docs/core/tools.mdx @@ -0,0 +1,286 @@ +--- +title: "Tools" +description: "Enable LLMs to perform actions through your server" +--- + +Tools are a powerful primitive in the Model Context Protocol (MCP) that enable servers to expose executable functionality to clients. Through tools, LLMs can interact with external systems, perform computations, and take actions in the real world. + +## How tools work + +Tools in MCP follow a request-response pattern where: + +1. Clients discover available tools through the `tools/list` endpoint +2. Clients can invoke tools using the `tools/call` endpoint +3. Servers execute the requested operation and return results +4. Progress updates can be sent during long-running operations + +## Tool definition structure + +Each tool is defined with the following structure: + +```typescript +{ + name: string; // Unique identifier for the tool + description?: string; // Human-readable description + inputSchema: { // JSON Schema for the tool's parameters + type: "object", + properties: { + // Tool-specific parameters + } + } +} +``` + +The `inputSchema` uses JSON Schema to define the expected parameters and their types. This enables: + +- Parameter validation +- Type checking +- Documentation of required vs optional parameters +- Complex nested parameter structures + +## Implementing tools + +Here's an example of implementing a basic tool in an MCP server: + +```typescript +const server = new Server({ + name: "example-server", + version: "1.0.0" +}); + +// Define available tools +server.setRequestHandler(ListToolsRequestSchema, async () => { + return { + tools: [{ + name: "calculate_sum", + description: "Add two numbers together", + inputSchema: { + type: "object", + properties: { + a: { type: "number" }, + b: { type: "number" } + }, + required: ["a", "b"] + } + }] + }; +}); + +// Handle tool execution +server.setRequestHandler(CallToolRequestSchema, async (request) => { + if (request.params.name === "calculate_sum") { + const { a, b } = request.params.arguments; + return { + toolResult: a + b + }; + } + throw new Error("Tool not found"); +}); +``` + +## Progress reporting + +For long-running operations, tools can report progress using the progress notification system: + +```typescript +server.setRequestHandler(CallToolRequestSchema, async (request) => { + if (request.params.name === "long_process") { + const progressToken = request.params._meta?.progressToken; + + for (let i = 0; i < total; i++) { + await doWork(); + + // Send progress update + await server.notification({ + method: "notifications/progress", + params: { + progress: i, + total: total, + progressToken + } + }); + } + + return { toolResult: "Complete" }; + } +}); +``` + +## Common tool patterns + +Here are some common patterns for implementing tools: + +### System operations + +Tools that interact with the local system: + +```typescript +{ + name: "execute_command", + description: "Run a shell command", + inputSchema: { + type: "object", + properties: { + command: { type: "string" }, + args: { type: "array", items: { type: "string" } } + } + } +} +``` + +### API integrations + +Tools that wrap external APIs: + +```typescript +{ + name: "github_create_issue", + description: "Create a GitHub issue", + inputSchema: { + type: "object", + properties: { + title: { type: "string" }, + body: { type: "string" }, + labels: { type: "array", items: { type: "string" } } + } + } +} +``` + +### Data processing + +Tools that transform or analyze data: + +```typescript +{ + name: "analyze_csv", + description: "Analyze a CSV file", + inputSchema: { + type: "object", + properties: { + filepath: { type: "string" }, + operations: { + type: "array", + items: { + enum: ["sum", "average", "count"] + } + } + } + } +} +``` + +## Best practices + +When implementing tools: + +1. Provide clear, descriptive names and descriptions +2. Use detailed JSON Schema definitions for parameters +3. Include examples in tool descriptions when helpful +4. Implement proper error handling and validation +5. Use progress reporting for long operations +6. Keep tool operations focused and atomic +7. Document expected return value structures +8. Implement proper timeouts +9. Consider rate limiting for resource-intensive operations +10. Log tool usage for debugging and monitoring + +## Security considerations + +When exposing tools: + +### Input validation + +- Validate all parameters against the schema +- Sanitize file paths and system commands +- Validate URLs and external identifiers +- Check parameter sizes and ranges +- Prevent command injection + +### Access control + +- Implement authentication where needed +- Use appropriate authorization checks +- Audit tool usage +- Rate limit requests +- Monitor for abuse + +### Error handling + +- Don't expose internal errors to clients +- Log security-relevant errors +- Handle timeouts appropriately +- Clean up resources after errors +- Validate return values + +## Tool discovery and updates + +MCP supports dynamic tool discovery: + +1. Clients can list available tools at any time +2. Servers can notify clients when tools change using `notifications/tools/list_changed` +3. Tools can be added or removed during runtime +4. Tool definitions can be updated (though this should be done carefully) + +## Common tool categories + +Tools typically fall into these categories: + +### System integration +- File operations +- Process management +- System information +- Network operations + +### External services +- API calls +- Database operations +- Authentication services +- Cloud services + +### Data processing +- Format conversion +- Data analysis +- Content generation +- Media processing + +### Device control +- Hardware interaction +- Device configuration +- Sensor reading +- Output control + +## Error handling + +Tools should return clear error information: + +```typescript +try { + // Tool operation +} catch (error) { + return { + toolResult: { + error: { + code: "OPERATION_FAILED", + message: "Failed to process request", + details: error.message + } + } + }; +} +``` + +## Testing tools + +Consider these testing approaches: + +1. Unit test parameter validation +2. Mock external dependencies +3. Test progress reporting +4. Verify error handling +5. Test concurrent execution +6. Validate return values +7. Test rate limiting +8. Check resource cleanup +9. Test timeout handling +10. Verify security constraints \ No newline at end of file diff --git a/docs/core/transport.mdx b/docs/core/transport.mdx new file mode 100644 index 0000000..e9e117c --- /dev/null +++ b/docs/core/transport.mdx @@ -0,0 +1,278 @@ +--- +title: "Transport" +description: "Learn about MCP's communication mechanisms" +--- + +Transport in the Model Context Protocol (MCP) provides the foundation for communication between clients and servers. It handles the underlying mechanics of how messages are sent and received. + +## How transport works + +MCP transport is built on a simple message-passing architecture where both clients and servers can send messages to each other. The transport layer is responsible for: + +- Establishing connections +- Sending messages +- Receiving messages +- Handling connection lifecycles +- Managing errors +- Ensuring reliable delivery + +## Available transport types + +MCP supports three main transport types: + +### Standard input/output (stdio) + +The stdio transport enables communication through standard input and output streams. This is particularly useful for local integrations and command-line tools. + +```typescript +// Server implementation +const server = new Server({ + name: "example-server", + version: "1.0.0" +}); + +const transport = new StdioServerTransport(); +await server.connect(transport); + +// Client implementation +const client = new Client({ + name: "example-client", + version: "1.0.0" +}); + +const transport = new StdioClientTransport({ + command: "./server", + args: ["--option", "value"] +}); +await client.connect(transport); +``` + +### WebSocket + +WebSocket transport provides real-time, bidirectional communication over a persistent connection. This is ideal for web-based applications that need low-latency messaging. + +```typescript +// Server implementation +const server = new Server({ + name: "example-server", + version: "1.0.0" +}); + +const transport = new WebSocketServerTransport(); +await server.connect(transport); + +// Client implementation +const client = new Client({ + name: "example-client", + version: "1.0.0" +}); + +const transport = new WebSocketClientTransport( + new URL("ws://localhost:3000") +); +await client.connect(transport); +``` + +### Server-sent events (SSE) + +SSE transport enables server-to-client streaming with HTTP POST requests for client-to-server communication. This is useful when WebSocket support isn't available. + +```typescript +// Server implementation +const server = new Server({ + name: "example-server", + version: "1.0.0" +}); + +const transport = new SSEServerTransport("/message", response); +await server.connect(transport); + +// Client implementation +const client = new Client({ + name: "example-client", + version: "1.0.0" +}); + +const transport = new SSEClientTransport( + new URL("http://localhost:3000/sse") +); +await client.connect(transport); +``` + +## Transport interface + +All transport implementations must conform to the Transport interface: + +```typescript +interface Transport { + // Start processing messages + start(): Promise; + + // Send a JSON-RPC message + send(message: JSONRPCMessage): Promise; + + // Close the connection + close(): Promise; + + // Callbacks + onclose?: () => void; + onerror?: (error: Error) => void; + onmessage?: (message: JSONRPCMessage) => void; +} +``` + +## Message format + +Messages sent over MCP transport follow the JSON-RPC 2.0 specification. There are three types of messages: + +### Requests + +```typescript +{ + jsonrpc: "2.0", + id: number | string, + method: string, + params?: object +} +``` + +### Responses + +```typescript +{ + jsonrpc: "2.0", + id: number | string, + result?: object, + error?: { + code: number, + message: string, + data?: unknown + } +} +``` + +### Notifications + +```typescript +{ + jsonrpc: "2.0", + method: string, + params?: object +} +``` + +## Error handling + +Transport implementations should handle various error scenarios: + +1. Connection errors +2. Message parsing errors +3. Protocol errors +4. Network timeouts +5. Resource cleanup + +Example error handling: + +```typescript +class ExampleTransport implements Transport { + async start() { + try { + // Connection logic + } catch (error) { + this.onerror?.(new Error(`Failed to connect: ${error}`)); + throw error; + } + } + + async send(message: JSONRPCMessage) { + try { + // Sending logic + } catch (error) { + this.onerror?.(new Error(`Failed to send message: ${error}`)); + throw error; + } + } +} +``` + +## Best practices + +When implementing or using MCP transport: + +1. Handle connection lifecycle properly +2. Implement proper error handling +3. Clean up resources on connection close +4. Use appropriate timeouts +5. Validate messages before sending +6. Log transport events for debugging +7. Implement reconnection logic when appropriate +8. Handle backpressure in message queues +9. Monitor connection health +10. Implement proper security measures + +## Security considerations + +When implementing transport: + +### Authentication and authorization + +- Implement proper authentication mechanisms +- Validate client credentials +- Use secure token handling +- Implement authorization checks + +### Data security + +- Use TLS for network transport +- Encrypt sensitive data +- Validate message integrity +- Implement message size limits +- Sanitize input data + +### Network security + +- Implement rate limiting +- Use appropriate timeouts +- Handle denial of service scenarios +- Monitor for unusual patterns +- Implement proper firewall rules + +## Debugging transport + +Tips for debugging transport issues: + +1. Enable debug logging +2. Monitor message flow +3. Check connection states +4. Validate message formats +5. Test error scenarios +6. Use network analysis tools +7. Implement health checks +8. Monitor resource usage +9. Test edge cases +10. Use proper error tracking + +## Transport selection guide + +Choose the appropriate transport based on your needs: + +### Use stdio when: + +- Building command-line tools +- Implementing local integrations +- Needing simple process communication +- Working with shell scripts + +### Use WebSocket when: + +- Real-time updates are needed +- Low latency is required +- Bidirectional communication is necessary +- Working with web applications + +### Use SSE when: + +- Only server-to-client streaming is needed +- WebSocket support is limited +- Working with restricted networks +- Implementing simple updates \ No newline at end of file diff --git a/docs/guides/claude.mdx b/docs/guides/claude.mdx new file mode 100644 index 0000000..8c862f0 --- /dev/null +++ b/docs/guides/claude.mdx @@ -0,0 +1,235 @@ +--- +title: "Connecting MCP to Claude" +description: "Get started with MCP in less than 5 minutes" +--- + +Give Claude superpowers by connecting it to your local computer! This guide will show you how to set up Model Context Protocol (MCP) and experience its magic in just 5 minutes. + + +MCP connects Claude to external data sources and tools. In this guide, we'll give Claude the ability to: +- Take screenshots and analyze them +- Control window arrangement +- Execute local automation scripts + +And it does this all securely - Claude can only access what you explicitly allow through MCP servers. + + +## Prerequisites + +- macOS (Windows/Linux guides coming soon) +- Node.js v16 or higher (`node --version` to check) +- Git (`git --version` to check) +- [Claude desktop app](https://claude.ai/download) installed + + +```bash +# Using Homebrew +brew install node git + +# Or download directly: +# Node.js: https://nodejs.org +# Git: https://git-scm.com +``` + + +## Installation + + + + Let's start by getting some pre-built MCP servers that Claude can use: + + ```bash + # Clone the example servers + git clone https://github.com/modelcontextprotocol/example-servers + cd example-servers + + # Install dependencies and build + npm install + npm run build + + # Make servers available globally + npm install -g + ``` + + + + Open your Claude Desktop App configuration: + + ```bash + code ~/Library/Application\ Support/Claude/claude_desktop_config.json + ``` + + Add this configuration (replace YOUR_USERNAME with your actual username): + + ```json + { + "mcpServers": { + "osascript": { + "command": "mcp-server-osascript", + } + } + } + ``` + + Save and **restart Claude Desktop App**. + + + +## Test it out + +Let's verify everything is working with a simple example. Try sending this prompt to Claude: + +``` +Can you take a screenshot of my desktop and describe what you see? +``` + +Claude will: + +1. Request permission to take a screenshot +2. Capture your screen through the MCP server +3. Analyze and describe the screenshot + + + Example Claude conversation showing a screenshot analysis + + +The first time you use screenshot features, macOS will ask for permissions: +- Screen Recording (for screenshots) +- Automation (for window control) +You'll need to grant these to Claude.app in System Settings. + + +## Try these examples + +Now that MCP is working, try these increasingly powerful examples: + + + + ``` + Could you analyze my open windows and tell me: + - How many windows I have open + - Which apps are running + - If any windows look cluttered + ``` + + + ``` + Could you help organize my windows? I'd like: + - Browser on the left half + - VSCode on the right half + ``` + + + ``` + I often need this window layout for coding: + - VSCode taking up the left 60% + - Terminal in the top right + - Browser in the bottom right + Could you create an AppleScript to automate this? + ``` + + + +## What just happened? + +Let's break down the magic: + +1. When you installed the `osascript` server, you gave Claude a way to: + - Take screenshots (see what you see) + - Run AppleScript (control your windows) + - Automate macOS tasks + +2. The MCP protocol lets Claude: + - Request these actions securely + - Get results back in real-time + - Chain actions together intelligently + +3. All of this happens locally on your machine - no data leaves your computer! + +## Add more capabilities + +Want to give Claude even more superpowers? Add these servers to your configuration: + + + Add this to your config to let Claude read and analyze files: + ```json + "tee": { + "command": "mcp-server-tee", + "args": ["tail", "-f", "/var/log/system.log"], + "env": { + "HOME": "/Users/YOUR_USERNAME" + } + } + ``` + + + + Connect Claude to your PostgreSQL database: + ```json + "postgres": { + "command": "mcp-server-postgres", + "args": ["postgresql://localhost/mydb"], + "env": { + "HOME": "/Users/YOUR_USERNAME" + } + } + ``` + + + + Enable web automation capabilities: + ```json + "puppeteer": { + "command": "mcp-server-puppeteer", + } + ``` + + + +## Troubleshooting + + + + 1. Check if MCP is enabled: + - Click the 🔌 icon in Claude + - You should see your configured servers + + 2. Verify your config: + ```bash + cat ~/Library/Application\ Support/Claude/claude_desktop_config.json + ``` + + 3. Restart Claude completely: + - Quit the app (not just close the window) + - Start it again + + + + Run this command to see Claude's logs: + ```bash + tail -f ~/Claude.log + ``` + + Common fixes: + - Check `HOME` env variable in your config + - Grant missing permissions in System Settings + - Try running example commands manually in Terminal + + + +## Next Steps + + + + Create your own MCP integrations to give Claude new capabilities. + + + + Browse our collection of example servers to see what's possible. + + + + Share your MCP creations and connect with other developers. + [Join us →](/community) + + diff --git a/docs/guides/first-server-python.mdx b/docs/guides/first-server-python.mdx new file mode 100644 index 0000000..7c512a2 --- /dev/null +++ b/docs/guides/first-server-python.mdx @@ -0,0 +1,422 @@ +--- +title: "Your First MCP Server (Python)" +description: "Create a simple MCP server in Python in 15 minutes" +--- + +Let's build your first MCP server in Python! We'll create a weather server that provides current weather data as a resource and lets Claude fetch forecasts using tools. + + +This guide uses the OpenWeatherMap API. You'll need a free API key from [OpenWeatherMap](https://openweathermap.org/api) to follow along. + + +## Prerequisites + + + + You'll need Python 3.8 or higher: + + ```bash + python3 --version # Should be 3.8 or higher + ``` + + + + ```bash + # Create and activate virtual environment + python3 -m venv mcp-weather + cd mcp-weather + source bin/activate # On Windows: .\Scripts\activate + ``` + + + + ```bash + pip install modelcontextprotocol-sdk requests + ``` + + + + 1. Sign up at [OpenWeatherMap](https://openweathermap.org/api) + 2. Copy your API key + 3. Set it as an environment variable: + ```bash + export OPENWEATHER_API_KEY='your-api-key' + ``` + + + +## Create your server + + + + ```bash + mkdir weather_server + cd weather_server + touch weather_server.py + ``` + + + + Open `weather_server.py` and add this starter code: + + ```python + from modelcontextprotocol.server import Server + from modelcontextprotocol.server.stdio import StdioServerTransport + from modelcontextprotocol.types import ( + ListResourcesRequestSchema, + ListToolsRequestSchema, + ReadResourceRequestSchema, + CallToolRequestSchema + ) + import os + import requests + import json + from datetime import datetime + + API_KEY = os.getenv('OPENWEATHER_API_KEY') + BASE_URL = 'http://api.openweathermap.org/data/2.5' + + class WeatherServer: + def __init__(self): + self.server = Server( + name="example-weather-server", + version="0.1.0" + ) + self.default_city = "San Francisco" + self.setup_handlers() + + def setup_handlers(self): + # We'll add handlers here + pass + + async def run(self): + transport = StdioServerTransport() + await self.server.connect(transport) + + if __name__ == "__main__": + import asyncio + server = WeatherServer() + asyncio.run(server.run()) + ``` + + + + Let's add handlers to expose current weather as a resource: + + ```python + def setup_handlers(self): + self.server.set_request_handler( + ListResourcesRequestSchema, + self.handle_list_resources + ) + self.server.set_request_handler( + ReadResourceRequestSchema, + self.handle_read_resource + ) + + async def handle_list_resources(self, request): + return { + "resources": [{ + "uri": f"weather://{self.default_city}/current", + "name": f"Current weather in {self.default_city}", + "mimeType": "application/json" + }] + } + + async def handle_read_resource(self, request): + city = self.default_city + if request.params.uri != f"weather://{city}/current": + raise ValueError(f"Unknown resource: {request.params.uri}") + + response = requests.get( + f"{BASE_URL}/weather", + params={ + "q": city, + "appid": API_KEY, + "units": "metric" + } + ) + data = response.json() + + return { + "contents": [{ + "uri": request.params.uri, + "mimeType": "application/json", + "text": json.dumps({ + "temperature": data["main"]["temp"], + "conditions": data["weather"][0]["description"], + "humidity": data["main"]["humidity"], + "wind_speed": data["wind"]["speed"], + "timestamp": datetime.now().isoformat() + }, indent=2) + }] + } + ``` + + + + Now let's add a tool to fetch weather forecasts: + + ```python + def setup_handlers(self): + # Add these lines to the existing method + self.server.set_request_handler( + ListToolsRequestSchema, + self.handle_list_tools + ) + self.server.set_request_handler( + CallToolRequestSchema, + self.handle_call_tool + ) + + async def handle_list_tools(self, request): + return { + "tools": [{ + "name": "get_forecast", + "description": "Get weather forecast for a city", + "inputSchema": { + "type": "object", + "properties": { + "city": { + "type": "string", + "description": "City name" + }, + "days": { + "type": "number", + "description": "Number of days (1-5)" + } + }, + "required": ["city"] + } + }] + } + + async def handle_call_tool(self, request): + if request.params.name != "get_forecast": + raise ValueError(f"Unknown tool: {request.params.name}") + + args = request.params.arguments + city = args.get("city", self.default_city) + days = min(int(args.get("days", 3)), 5) + + response = requests.get( + f"{BASE_URL}/forecast", + params={ + "q": city, + "appid": API_KEY, + "units": "metric", + "cnt": days * 8 # API returns 3-hour intervals + } + ) + data = response.json() + + # Process and return daily forecasts + forecasts = [] + for i in range(0, len(data["list"]), 8): # One day = 8 intervals + day_data = data["list"][i] + forecasts.append({ + "date": day_data["dt_txt"].split()[0], + "temperature": day_data["main"]["temp"], + "conditions": day_data["weather"][0]["description"] + }) + + return {"toolResult": forecasts} + ``` + + + + 1. Save all changes + 2. Run your server: + ```bash + python weather_server.py + ``` + + + +## Connect to Claude + + + + ```bash + # From your project directory + pip install -e . + ``` + + + + Add this to your `claude_desktop_config.json`: + + ```json + { + "mcpServers": { + "weather": { + "command": "python", + "args": ["-m", "weather_server"], + "env": { + "OPENWEATHER_API_KEY": "your-api-key", + "HOME": "/Users/YOUR_USERNAME" + } + } + } + } + ``` + + + + 1. Quit Claude completely + 2. Start Claude again + 3. Verify your weather server appears in the 🔌 menu + + + +## Try it out! + + + + Ask Claude: + ``` + What's the current weather in San Francisco? Can you analyze the conditions? + ``` + + Claude will: + 1. Access the weather resource + 2. Parse the JSON data + 3. Provide a natural language summary + + + + Ask Claude: + ``` + Can you get me a 5-day forecast for Tokyo and tell me if I should pack an umbrella? + ``` + + Claude will: + 1. Use the `get_forecast` tool + 2. Analyze the forecast data + 3. Give you packing advice + + + +## Understanding the code + +Let's break down the key MCP concepts used in this server: + + + + ```python + async def handle_list_resources(self, request): + return { + "resources": [{ + "uri": f"weather://{self.default_city}/current", + "name": f"Current weather in {self.default_city}", + "mimeType": "application/json" + }] + } + ``` + Resources provide data that Claude can access as context. In this case, we're exposing current weather data that Claude can read and analyze. + + + + ```python + async def handle_list_tools(self, request): + return { + "tools": [{ + "name": "get_forecast", + "description": "Get weather forecast for a city", + "inputSchema": { + "type": "object", + "properties": { + "city": {"type": "string"}, + "days": {"type": "number"} + } + } + }] + } + ``` + Tools let Claude take actions through your server. The `inputSchema` defines what parameters Claude can provide. + + + + ```python + async def run(self): + transport = StdioServerTransport() + await self.server.connect(transport) + ``` + The transport layer handles communication between Claude and your server. Here we're using stdio, but MCP also supports WebSocket and SSE. + + + +## Next steps + +Now that you've built your first MCP server, try these enhancements: + + + + - Air quality data + - Weather alerts + - Historical weather + + + + - Compare multiple cities + - Get detailed hourly forecasts + - Save favorite locations + + + + - Handle API errors gracefully + - Add input validation + - Rate limiting + + + + - Weather alerts + - Temperature changes + - Condition updates + + + +## Troubleshooting + + + + ```bash + pip install modelcontextprotocol-sdk --upgrade + ``` + Ensure you're using the latest SDK version. + + + + 1. Verify your API key is set: + ```bash + echo $OPENWEATHER_API_KEY + ``` + 2. Check the API response for error messages + 3. Ensure you're within free tier limits + + + + 1. Check Claude's logs: + ```bash + tail -f ~/Claude.log + ``` + 2. Verify your config JSON syntax + 3. Ensure Python path is correct in config + + + + +Remember: This is just the beginning! MCP servers can provide any type of data or functionality to Claude. Think about what unique capabilities you could add to Claude through MCP. + \ No newline at end of file diff --git a/docs/guides/first-server-ts.mdx b/docs/guides/first-server-ts.mdx new file mode 100644 index 0000000..d3e0656 --- /dev/null +++ b/docs/guides/first-server-ts.mdx @@ -0,0 +1,533 @@ +--- +title: "Your First MCP Server (TypeScript)" +description: "Create a simple MCP server in TypeScript in 15 minutes" +--- + +Let's build your first MCP server in TypeScript! We'll create a weather server that provides current weather data as a resource and lets Claude fetch forecasts using tools. + + +This guide uses the OpenWeatherMap API. You'll need a free API key from [OpenWeatherMap](https://openweathermap.org/api) to follow along. + + +## Prerequisites + + + + You'll need Node.js 16 or higher: + + ```bash + node --version # Should be v16 or higher + npm --version + ``` + + + + ```bash + mkdir weather-server + cd weather-server + npm init -y + ``` + + + + ```bash + npm install @modelcontextprotocol/sdk axios dotenv typescript @types/node + npm install --save-dev ts-node + ``` + + + + Create `tsconfig.json`: + ```json + { + "compilerOptions": { + "target": "ES2020", + "module": "ES2020", + "moduleResolution": "node", + "esModuleInterop": true, + "outDir": "./dist", + "rootDir": "./src", + "strict": true + }, + "include": ["src/**/*"] + } + ``` + + + + Create `.env`: + ```bash + OPENWEATHER_API_KEY=your-api-key-here + ``` + + + +## Create your server + + + + ```bash + mkdir src + touch src/index.ts + touch src/types.ts + ``` + + + + In `src/types.ts`: + + ```typescript + export interface WeatherData { + temperature: number; + conditions: string; + humidity: number; + wind_speed: number; + timestamp: string; + } + + export interface ForecastDay { + date: string; + temperature: number; + conditions: string; + } + + export interface GetForecastArgs { + city: string; + days?: number; + } + ``` + + + + In `src/index.ts`: + + ```typescript + import { Server } from "@modelcontextprotocol/sdk/server/index.js"; + import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; + import axios from "axios"; + import dotenv from "dotenv"; + import { WeatherData, ForecastDay, GetForecastArgs } from "./types.js"; + + dotenv.config(); + + const API_KEY = process.env.OPENWEATHER_API_KEY; + const BASE_URL = 'http://api.openweathermap.org/data/2.5'; + const DEFAULT_CITY = 'San Francisco'; + + class WeatherServer { + private server: Server; + + constructor() { + this.server = new Server({ + name: "example-weather-server", + version: "0.1.0" + }); + this.setupHandlers(); + } + + private setupHandlers(): void { + // We'll add handlers here + } + + async run(): Promise { + const transport = new StdioServerTransport(); + await this.server.connect(transport); + } + } + + const server = new WeatherServer(); + server.run().catch(console.error); + ``` + + + + Add this to the `setupHandlers` method: + + ```typescript + private setupHandlers(): void { + this.server.setRequestHandler( + ListResourcesRequestSchema, + async () => ({ + resources: [{ + uri: `weather://${DEFAULT_CITY}/current`, + name: `Current weather in ${DEFAULT_CITY}`, + mimeType: "application/json" + }] + }) + ); + + this.server.setRequestHandler( + ReadResourceRequestSchema, + async (request) => { + const city = DEFAULT_CITY; + if (request.params.uri !== `weather://${city}/current`) { + throw new Error(`Unknown resource: ${request.params.uri}`); + } + + const response = await axios.get(`${BASE_URL}/weather`, { + params: { + q: city, + appid: API_KEY, + units: "metric" + } + }); + + const weatherData: WeatherData = { + temperature: response.data.main.temp, + conditions: response.data.weather[0].description, + humidity: response.data.main.humidity, + wind_speed: response.data.wind.speed, + timestamp: new Date().toISOString() + }; + + return { + contents: [{ + uri: request.params.uri, + mimeType: "application/json", + text: JSON.stringify(weatherData, null, 2) + }] + }; + } + ); + } + ``` + + + + Add these handlers to the `setupHandlers` method: + + ```typescript + this.server.setRequestHandler( + ListToolsRequestSchema, + async () => ({ + tools: [{ + name: "get_forecast", + description: "Get weather forecast for a city", + inputSchema: { + type: "object", + properties: { + city: { + type: "string", + description: "City name" + }, + days: { + type: "number", + description: "Number of days (1-5)" + } + }, + required: ["city"] + } + }] + }) + ); + + this.server.setRequestHandler( + CallToolRequestSchema, + async (request) => { + if (request.params.name !== "get_forecast") { + throw new Error(`Unknown tool: ${request.params.name}`); + } + + const args = request.params.arguments as GetForecastArgs; + const city = args.city || DEFAULT_CITY; + const days = Math.min(args.days || 3, 5); + + const response = await axios.get(`${BASE_URL}/forecast`, { + params: { + q: city, + appid: API_KEY, + units: "metric", + cnt: days * 8 // API returns 3-hour intervals + } + }); + + const forecasts: ForecastDay[] = []; + for (let i = 0; i < response.data.list.length; i += 8) { + const dayData = response.data.list[i]; + forecasts.push({ + date: dayData.dt_txt.split(' ')[0], + temperature: dayData.main.temp, + conditions: dayData.weather[0].description + }); + } + + return { toolResult: forecasts }; + } + ); + ``` + + + + Add these scripts to `package.json`: + ```json + { + "scripts": { + "build": "tsc", + "start": "node dist/index.js", + "dev": "ts-node src/index.ts" + } + } + ``` + + Then run: + ```bash + npm run build + npm start + ``` + + + +## Connect to Claude + + + + ```bash + npm install -g + ``` + + + + Add to `claude_desktop_config.json`: + + ```json + { + "mcpServers": { + "weather": { + "command": "weather-server", + "env": { + "OPENWEATHER_API_KEY": "your-api-key", + "HOME": "/Users/YOUR_USERNAME" + } + } + } + } + ``` + + + + 1. Quit Claude completely + 2. Start Claude again + 3. Look for your weather server in the 🔌 menu + + + +## Try it out! + + + + Ask Claude: + ``` + What's the current weather in San Francisco? Can you analyze the conditions? + ``` + + + + Ask Claude: + ``` + Can you get me a 5-day forecast for Tokyo and tell me if I should pack an umbrella? + ``` + + + + Ask Claude: + ``` + Can you analyze the forecast for both Tokyo and San Francisco and tell me which city will be warmer this week? + ``` + + + +## Understanding the code + + + + ```typescript + interface WeatherData { + temperature: number; + conditions: string; + humidity: number; + wind_speed: number; + timestamp: string; + } + ``` + TypeScript adds type safety to our MCP server, making it more reliable and easier to maintain. + + + + ```typescript + this.server.setRequestHandler( + ListResourcesRequestSchema, + async () => ({ + resources: [{ + uri: `weather://${DEFAULT_CITY}/current`, + name: `Current weather in ${DEFAULT_CITY}`, + mimeType: "application/json" + }] + }) + ); + ``` + Resources provide data that Claude can access as context. + + + + ```typescript + { + name: "get_forecast", + description: "Get weather forecast for a city", + inputSchema: { + type: "object", + properties: { + city: { type: "string" }, + days: { type: "number" } + } + } + } + ``` + Tools let Claude take actions through your server with type-safe inputs. + + + +## Best practices + + + + ```typescript + try { + const response = await axios.get(url); + } catch (error) { + if (axios.isAxiosError(error)) { + throw new Error(`API error: ${error.response?.data.message}`); + } + throw error; + } + ``` + + + + ```typescript + function isValidForecastArgs(args: unknown): args is GetForecastArgs { + return typeof args === "object" && args !== null && + "city" in args; + } + ``` + + + + ```typescript + if (!process.env.OPENWEATHER_API_KEY) { + throw new Error("OPENWEATHER_API_KEY is required"); + } + ``` + + + + ```typescript + const API_ENDPOINTS = { + CURRENT: "weather", + FORECAST: "forecast" + } as const; + ``` + + + +## Enhancements + +Try adding these features to your server: + + + + Add dynamic city resources: + ```typescript + uriTemplate: "weather://{city}/current" + ``` + + + + Cache API responses: + ```typescript + import NodeCache from "node-cache" + ``` + + + + Add API rate limiting: + ```typescript + import rateLimit from "axios-rate-limit" + ``` + + + +## Troubleshooting + + + + ```bash + # Check TypeScript version + npx tsc --version + + # Clean and rebuild + rm -rf dist/ + npm run build + ``` + + + + Add better error logging: + ```typescript + server.onerror = (error) => { + console.error("[MCP Error]", error); + }; + ``` + + + + ```bash + # Check types without building + npx tsc --noEmit + ``` + + + +## Next steps + + + + Switch to real-time updates with WebSocket transport + + + + Add Jest tests for your MCP server + + + + +Need help? Ask Claude! Since it has access to the MCP SDK documentation, it can help you debug issues and suggest improvements to your server. + \ No newline at end of file diff --git a/docs/guides/integrate-python.mdx b/docs/guides/integrate-python.mdx new file mode 100644 index 0000000..e84e9de --- /dev/null +++ b/docs/guides/integrate-python.mdx @@ -0,0 +1,442 @@ +--- +title: "Integrate MCP into Your Python App" +description: "Add MCP support to your LLM application in Python" +--- + +Learn how to integrate MCP into your Python LLM application. We'll build a simple web analyzer that uses Claude to analyze websites, enhanced with MCP's web automation capabilities. + + +This guide uses an existing MCP server ([puppeteer](/servers/puppeteer)) rather than building one from scratch. This lets us focus on the integration patterns. + + +## The example app + +We'll build an "AI Web Analyzer" that: +1. Takes a URL from the user +2. Captures the webpage using MCP +3. Has the LLM analyze the page's content, design, and accessibility + + + Screenshot of the Web Analyzer CLI interface + + +## Prerequisites + + + + ```bash + pip install modelcontextprotocol-sdk anthropic click rich + ``` + + + + ```bash + # Install example MCP servers + git clone https://github.com/modelcontextprotocol/example-servers + cd example-servers + npm install + npm run build + npm install -g + ``` + + + + ```bash + # Set your Anthropic API key + export ANTHROPIC_API_KEY='your-key-here' + ``` + + + +## Building the base app + +First, let's create a basic version without MCP: + + + + ```bash + mkdir web-analyzer + cd web-analyzer + touch analyzer.py + ``` + + + + ```python + # analyzer.py + import click + import anthropic + from rich.console import Console + from rich.panel import Panel + from rich import print as rprint + + console = Console() + client = anthropic.Client() + + def analyze_url(url: str) -> str: + messages = [{ + "role": "user", + "content": f"Please analyze this website: {url}\n\n" + f"I'd like to know about:\n" + f"1. Content quality and organization\n" + f"2. Visual design (based on the URL/description)\n" + f"3. Potential improvements" + }] + + response = client.messages.create( + model="claude-3-opus-20240229", + max_tokens=1000, + messages=messages + ) + return response.content[0].text + + @click.command() + @click.argument('url') + def main(url: str): + with console.status("[bold green]Analyzing website..."): + analysis = analyze_url(url) + + rprint(Panel.fit( + analysis, + title="Website Analysis", + border_style="blue" + )) + + if __name__ == '__main__': + main() + ``` + + + + ```bash + python analyzer.py https://example.com + ``` + + + +## Adding MCP support + +Now let's enhance the app with MCP capabilities: + + + + ```python + # At the top of analyzer.py + from modelcontextprotocol.client import Client + from modelcontextprotocol.client.stdio import StdioClientTransport + import asyncio + import json + from typing import Optional + + class MCPWebClient: + def __init__(self): + self.client = Client( + client_info={ + "name": "web-analyzer", + "version": "0.1.0" + } + ) + self.transport = None + + async def connect(self): + self.transport = StdioClientTransport( + server={ + "command": "mcp-server-puppeteer", + } + ) + await self.client.connect(self.transport) + + async def navigate(self, url: str) -> Optional[str]: + try: + result = await self.client.request( + { + "method": "tools/call", + "params": { + "name": "navigate", + "arguments": {"url": url} + } + }, + schema=CallToolResultSchema + ) + return result.get("toolResult") + except Exception as e: + console.print(f"[red]Error navigating to URL: {e}") + return None + + async def get_console_logs(self) -> str: + result = await self.client.request( + { + "method": "resources/read", + "params": {"uri": "console://logs"} + }, + schema=ReadResourceResultSchema + ) + return result["contents"][0]["text"] + + async def close(self): + if self.transport: + await self.client.close() + ``` + + + ```python + async def analyze_url_with_mcp(url: str) -> str: + # Create and connect MCP client + mcp = MCPWebClient() + await mcp.connect() + # Navigate to the URL + await mcp.navigate(url) + + # Get console logs (includes errors, warnings, etc.) + console_logs = await mcp.get_console_logs() + + # Close the connection + await mcp.close() + + # Analyze with Claude + messages = [{ + "role": "user", + "content": ( + f"Please analyze this website: {url}\n\n" + f"Here are the browser console logs:\n{console_logs}\n\n" + f"Please analyze:\n" + f"1. Content quality and organization\n" + f"2. Visual design\n" + f"3. Technical issues (based on console logs)\n" + f"4. Potential improvements" + ) + }] + + response = client.messages.create( + model="claude-3-opus-20240229", + max_tokens=1000, + messages=messages + ) + return response.content[0].text + + @click.command() + @click.argument('url') + def main(url: str): + with console.status("[bold green]Analyzing website..."): + analysis = asyncio.run(analyze_url_with_mcp(url)) + + rprint(Panel.fit( + analysis, + title="Website Analysis", + border_style="blue" + )) + ``` + + + ```bash + python analyzer.py https://example.com + ``` + + + +## Understanding MCP integration + +Let's break down the key components of MCP integration: + + + ```python + class MCPWebClient: + def __init__(self): + self.client = Client( + client_info={ + "name": "web-analyzer", + "version": "0.1.0" + } + ) + ``` + The MCP client identifies your application and manages the connection to MCP servers. + + + ```python + self.transport = StdioClientTransport( + server={ + "command": "mcp-server-puppeteer", + } + ) + ``` + The transport layer handles communication with the MCP server. Here we're using stdio to talk to the puppeteer server. + + + ```python + result = await self.client.request( + { + "method": "tools/call", + "params": { + "name": "navigate", + "arguments": {"url": url} + } + }, + schema=CallToolResultSchema + ) + ``` + Tools let you take actions through MCP servers. Here we're using puppeteer's navigate tool. + + + ```python + result = await self.client.request( + { + "method": "resources/read", + "params": {"uri": "console://logs"} + }, + schema=ReadResourceResultSchema + ) + ``` + Resources provide data from MCP servers. Here we're reading console logs that puppeteer collected. + + + +## Enhancement ideas + +Now that you have MCP working, here are some ways to enhance the analyzer: + + + ```python + # Take screenshots with puppeteer + await client.request({ + "method": "tools/call", + "params": { + "name": "screenshot", + "arguments": {...} + } + }) + ``` + + + ```python + # Analyze multiple pages in sequence + for url in urls: + await navigate(url) + await analyze() + ``` + + + ```python + # Test interactive features + await client.request({ + "method": "tools/call", + "params": { + "name": "click", + "arguments": {"selector": "button"} + } + }) + ``` + + + +Common Patterns +Here are some patterns you'll often use when integrating MCP: + + + When you need to wait for resource updates: + ```python + async def wait_for_resource(uri: str, timeout: int = 30): + start = time.time() + while time.time() - start < timeout: + result = await client.request( + { + "method": "resources/read", + "params": {"uri": uri} + }, + schema=ReadResourceResultSchema + ) + if some_condition(result): + return result + await asyncio.sleep(1) + raise TimeoutError() + ``` + + + Robust error handling for MCP operations: + ```python + try: + await client.request(...) + except MCPError as e: + if e.code == ErrorCode.ResourceNotFound: + # Handle missing resource + elif e.code == ErrorCode.InvalidRequest: + # Handle invalid parameters + else: + # Handle other errors + ``` + + + Subscribe to resource updates: + ```python + await client.request( + { + "method": "resources/subscribe", + "params": {"uri": "console://logs"} + }, + schema=EmptyResultSchema + ) + # Now you'll get notifications when logs change + ``` + + + +## Troubleshooting + + + + ```python + # Enable debug logging + import logging + logging.basicConfig(level=logging.DEBUG) + ``` + Watch for connection errors and MCP protocol messages. + + + 1. Check if the resource exists: + ```python + resources = await client.request( + {"method": "resources/list"}, + schema=ListResourcesResultSchema + ) + print(resources) + ``` + 2. Verify URI format + 3. Check server logs + + + 1. List available tools: + ```python + tools = await client.request( + {"method": "tools/list"}, + schema=ListToolsResultSchema + ) + print(tools) + ``` + 2. Check argument schema + 3. Verify server capabilities + + + +## Next steps + + + + Connect to additional MCP servers for more capabilities + + +Create your own MCP server for custom functionality + + \ No newline at end of file diff --git a/docs/guides/integrate-ts.mdx b/docs/guides/integrate-ts.mdx new file mode 100644 index 0000000..fdb3a2e --- /dev/null +++ b/docs/guides/integrate-ts.mdx @@ -0,0 +1,885 @@ +--- +title: "Integrate MCP into Your TypeScript App" +description: "Add MCP support to your LLM application in TypeScript" +--- + +Learn how to integrate MCP into your TypeScript/React application. We'll build an AI Web Analyzer that uses Claude to analyze websites, enhanced with MCP's web automation capabilities. + + +This guide uses an existing MCP server ([puppeteer](/servers/puppeteer)) rather than building one from scratch. This lets us focus on the integration patterns. + + +## The example app + +We'll build an "AI Web Analyzer" that: +1. Takes a URL from the user +2. Captures the webpage using MCP +3. Has Claude analyze the page's content, design, and accessibility + + + Screenshot of the Web Analyzer interface + + +## Prerequisites + + + + ```bash + # Create new Next.js project with TypeScript + npx create-next-app@latest web-analyzer --typescript --tailwind + cd web-analyzer + ``` + + + + ```bash + npm install @modelcontextprotocol/sdk @anthropic-ai/sdk + ``` + + + + ```bash + # Install example MCP servers + git clone https://github.com/modelcontextprotocol/example-servers + cd example-servers + npm install + npm run build + npm install -g + ``` + + + +## Building the base app + +First, let's create a basic version without MCP: + + + + Create `components/WebAnalyzer.tsx`: + + ```tsx + import { useState } from 'react'; + import Anthropic from '@anthropic-ai/sdk'; + + const anthropic = new Anthropic({ + apiKey: process.env.NEXT_PUBLIC_ANTHROPIC_API_KEY + }); + + export default function WebAnalyzer() { + const [url, setUrl] = useState(''); + const [analysis, setAnalysis] = useState(''); + const [loading, setLoading] = useState(false); + + const analyzeUrl = async () => { + setLoading(true); + try { + const response = await anthropic.messages.create({ + model: 'claude-3-opus-20240229', + max_tokens: 1000, + messages: [{ + role: 'user', + content: `Please analyze this website: ${url}\n\n` + + `I'd like to know about:\n` + + `1. Content quality and organization\n` + + `2. Visual design (based on URL/description)\n` + + `3. Potential improvements` + }] + }); + setAnalysis(response.content[0].text); + } catch (error) { + console.error('Error:', error); + setAnalysis('Error analyzing website'); + } + setLoading(false); + }; + + return ( +
+

+ AI Web Analyzer +

+ +
+ setUrl(e.target.value)} + placeholder="Enter website URL" + className="flex-1 p-2 border rounded" + /> + +
+ + {loading && ( +
+ Analyzing website... +
+ )} + + {analysis && ( +
+
{analysis}
+
+ )} +
+ ); + } + ``` +
+ + + Update `app/page.tsx`: + + ```tsx + import WebAnalyzer from '@/components/WebAnalyzer'; + + export default function Home() { + return ( +
+ +
+ ); + } + ``` +
+ + + Create `.env.local`: + + ```bash + NEXT_PUBLIC_ANTHROPIC_API_KEY=your-key-here + ``` + +
+ +## Adding MCP support + +Now let's enhance the app with MCP capabilities: + + + + Create `lib/mcp.ts`: + + ```typescript + import { Client } from '@modelcontextprotocol/sdk/client'; + import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio'; + import { + CallToolResultSchema, + ReadResourceResultSchema + } from '@modelcontextprotocol/sdk/types'; + + export class MCPWebClient { + private client: Client; + private transport: StdioClientTransport | null = null; + + constructor() { + this.client = new Client({ + name: 'web-analyzer', + version: '0.1.0' + }); + } + + async connect() { + this.transport = new StdioClientTransport({ + command: 'mcp-server-puppeteer' + }); + await this.client.connect(this.transport); + } + + async navigate(url: string): Promise { + try { + const result = await this.client.request( + { + method: 'tools/call', + params: { + name: 'navigate', + arguments: { url } + } + }, + CallToolResultSchema + ); + return result.toolResult as string; + } catch (error) { + console.error('Error navigating:', error); + return null; + } + } + + async getConsoleLogs(): Promise { + const result = await this.client.request( + { + method: 'resources/read', + params: { uri: 'console://logs' } + }, + ReadResourceResultSchema + ); + return result.contents[0].text; + } + + async close() { + if (this.transport) { + await this.client.close(); + } + } + } + ``` + + + + Create `contexts/MCPContext.tsx`: + + ```typescript + import { createContext, useContext, useEffect, useRef } from 'react'; + import { MCPWebClient } from '@/lib/mcp'; + + const MCPContext = createContext(null); + + export function MCPProvider({ children }: { children: React.ReactNode }) { + const clientRef = useRef(null); + + useEffect(() => { + const initMCP = async () => { + clientRef.current = new MCPWebClient(); + await clientRef.current.connect(); + }; + + initMCP(); + + return () => { + if (clientRef.current) { + clientRef.current.close(); + } + }; + }, []); + + return ( + + {children} + + ); + } + + export function useMCP() { + const context = useContext(MCPContext); + if (!context) { + throw new Error('useMCP must be used within MCPProvider'); + } + return context; + } + ``` + + + + Update `components/WebAnalyzer.tsx`: + + ```typescript + import { useState } from 'react'; + import Anthropic from '@anthropic-ai/sdk'; + import { useMCP } from '@/contexts/MCPContext'; + + const anthropic = new Anthropic({ + apiKey: process.env.NEXT_PUBLIC_ANTHROPIC_API_KEY + }); + + export default function WebAnalyzer() { + const mcp = useMCP(); + const [url, setUrl] = useState(''); + const [analysis, setAnalysis] = useState(''); + const [loading, setLoading] = useState(false); + + const analyzeUrl = async () => { + setLoading(true); + try { + // Navigate to the URL with MCP + await mcp.navigate(url); + + // Get console logs + const consoleLogs = await mcp.getConsoleLogs(); + + // Analyze with Claude + const response = await anthropic.messages.create({ + model: 'claude-3-opus-20240229', + max_tokens: 1000, + messages: [{ + role: 'user', + content: `Please analyze this website: ${url}\n\n` + + `Here are the browser console logs:\n${consoleLogs}\n\n` + + `Please analyze:\n` + + `1. Content quality and organization\n` + + `2. Visual design\n` + + `3. Technical issues (based on console logs)\n` + + `4. Potential improvements` + }] + }); + setAnalysis(response.content[0].text); + } catch (error) { + console.error('Error:', error); + setAnalysis('Error analyzing website'); + } + setLoading(false); + }; + + // ... rest of the component remains the same + } + ``` + + + + Update `app/layout.tsx`: + + ```typescript + import { MCPProvider } from '@/contexts/MCPContext'; + + export default function RootLayout({ + children, + }: { + children: React.ReactNode + }) { + return ( + + + + {children} + + + + ); + } + ``` + + + +## Understanding MCP integration + +Let's break down the key components: + + + + ```typescript + export class MCPWebClient { + private client: Client; + + constructor() { + this.client = new Client({ + name: 'web-analyzer', + version: '0.1.0' + }); + } + } + ``` + The MCP client manages the connection to MCP servers and handles requests. + + + + ```typescript + export function MCPProvider({ children }: { children: React.ReactNode }) { + const clientRef = useRef(null); + + useEffect(() => { + const initMCP = async () => { + clientRef.current = new MCPWebClient(); + await clientRef.current.connect(); + }; + + initMCP(); + // ... cleanup + }, []); + } + ``` + The context provider manages the MCP client lifecycle. + + + + ```typescript + async navigate(url: string): Promise { + const result = await this.client.request( + { + method: 'tools/call', + params: { + name: 'navigate', + arguments: { url } + } + }, + CallToolResultSchema + ); + return result.toolResult as string; + } + ``` + Tools let you take actions through MCP servers. + + + + ```typescript + async getConsoleLogs(): Promise { + const result = await this.client.request( + { + method: 'resources/read', + params: { uri: 'console://logs' } + }, + ReadResourceResultSchema + ); + return result.contents[0].text; + } + ``` + Resources provide data from MCP servers. + + + +## Enhancement ideas + +Here are some ways to enhance the analyzer: + + + + ```typescript + // Add screenshot capability + async function captureScreenshot() { + const result = await mcp.client.request({ + method: 'tools/call', + params: { + name: 'screenshot', + arguments: { /* ... */ } + } + }); + } + ``` + + + + ```typescript + // Analyze multiple pages + async function analyzeBatch(urls: string[]) { + const results = []; + for (const url of urls) { + await mcp.navigate(url); + // ... analyze + } + } + ``` + + + + ```typescript + // Test interactive elements + async function testInteraction() { + await mcp.client.request({ + method: 'tools/call', + params: { + name: 'click', + arguments: { selector: 'button' } + } + }); + } + ``` + + + + ```typescript + // Add performance metrics + async function getPerformance() { + const metrics = await mcp.client.request({ + method: 'resources/read', + params: { uri: 'metrics://performance' } + }); + } + ``` + + + +## Common patterns + +Here are some patterns you'll often use with MCP in React: + + + + ```typescript + function useResourcePolling(uri: string, interval = 1000) { + const [data, setData] = useState(null); + + useEffect(() => { + let mounted = true; + + async function poll() { + while (mounted) { + const result = await mcp.client.request({ + method: 'resources/read', + params: { uri } + }); + if (mounted) { + setData(result); + await new Promise(r => setTimeout(r, interval)); + } + } + } + + poll(); + return () => { mounted = false; }; + }, [uri, interval]); + + return data; + } + ``` + + + + ```typescript + class MCPErrorBoundary extends React.Component { + state = { hasError: false }; + + static getDerivedStateFromError(error) { + return { hasError: true }; + } + + componentDidCatch(error, errorInfo) { + if (error instanceof MCPError) { + // Handle MCP-specific errors + } + } + + render() { + if (this.state.hasError) { + return ; + } + return this.props.children; + } + } + ``` + + + + ```typescript + function useResourceSubscription(uri: string) { + useEffect(() => { + mcp.client.request({ + method: 'resources/subscribe', + params: { uri } + }); + + return () => { + mcp.client.request({ + method: 'resources/unsubscribe', + params: { uri } + }); + }; + }, [uri]); + } + ``` + + + +## Troubleshooting + + + + ```typescript + // Enable debug logging + const initMCP = async () => { + const client = new MCPWebClient({ + debug: true, // Enable debug logging + onError: (error) => { + console.error('MCP Error:', error); + } + }); + await client.connect(); + }; + ``` + Watch the browser console for connection errors and protocol messages. + + + + Common issues and solutions: + ```typescript + function WebAnalyzer() { + // Don't create client on every render + const mcpRef = useRef(null); + + // Initialize in useEffect + useEffect(() => { + const init = async () => { + mcpRef.current = new MCPWebClient(); + await mcpRef.current.connect(); + }; + init(); + + // Clean up properly + return () => { + if (mcpRef.current) { + mcpRef.current.close(); + } + }; + }, []); + } + ``` + + + + Use TypeScript to catch MCP issues early: + ```typescript + // Define expected response types + interface ToolResponse { + toolResult: { + screenshot?: string; + logs?: string[]; + error?: string; + }; + } + + // Use with request + const result = await client.request({ + method: 'tools/call', + params: { + name: 'screenshot', + arguments: { /* ... */ } + } + }); + + // TypeScript will catch missing properties + console.log(result.toolResult.screenshot); + ``` + + + +## Performance optimization + + + + ```typescript + function useCachedResource(uri: string) { + const [data, setData] = useState(null); + const cache = useRef(new Map()); + + useEffect(() => { + async function fetchResource() { + if (cache.current.has(uri)) { + setData(cache.current.get(uri)!); + return; + } + + const result = await mcp.client.request({ + method: 'resources/read', + params: { uri } + }); + + cache.current.set(uri, result.contents[0].text); + setData(result.contents[0].text); + } + + fetchResource(); + }, [uri]); + + return data; + } + ``` + + + + ```typescript + class BatchedMCPClient extends MCPWebClient { + private batchQueue: Map>; + + async request(method: string, params: any) { + const key = JSON.stringify({ method, params }); + + if (!this.batchQueue.has(key)) { + this.batchQueue.set( + key, + super.request(method, params) + ); + + // Clear after resolution + this.batchQueue.get(key)!.finally(() => { + this.batchQueue.delete(key); + }); + } + + return this.batchQueue.get(key); + } + } + ``` + + + +## Building for production + + + + Add proper error boundaries: + + ```typescript + import { ErrorBoundary } from 'react-error-boundary'; + + function ErrorFallback({ error, resetErrorBoundary }) { + return ( +
+

Something went wrong:

+
{error.message}
+ +
+ ); + } + + export default function App() { + return ( + { + // Reset application state + }} + > + + + ); + } + ``` +
+ + + Add proper loading indicators: + + ```typescript + function WebAnalyzer() { + const [state, setState] = useState<{ + status: 'idle' | 'loading' | 'success' | 'error'; + error?: Error; + data?: string; + }>({ + status: 'idle' + }); + + return ( +
+ {state.status === 'loading' && ( +
+
+
+
+
+
+
+ )} + + {state.status === 'error' && ( +
+ {state.error?.message} +
+ )} + + {state.status === 'success' && ( +
{state.data}
+ )} +
+ ); + } + ``` +
+ + + Set up proper environment variables: + + ```typescript + // next.config.js + module.exports = { + env: { + NEXT_PUBLIC_ANTHROPIC_API_KEY: process.env.NEXT_PUBLIC_ANTHROPIC_API_KEY, + MCP_DEBUG: process.env.NODE_ENV === 'development' + } + }; + + // Usage in code + const mcpClient = new MCPWebClient({ + debug: process.env.MCP_DEBUG === 'true' + }); + ``` + +
+ +## Security considerations + + +Always validate and sanitize URLs before passing them to MCP servers. The puppeteer server has access to execute JavaScript and interact with web pages. + + +```typescript +function validateUrl(url: string): boolean { + try { + const parsed = new URL(url); + // Add your validation rules + return parsed.protocol === 'https:'; + } catch { + return false; + } +} + +function WebAnalyzer() { + const analyzeUrl = async () => { + if (!validateUrl(url)) { + setError('Please enter a valid HTTPS URL'); + return; + } + // ... rest of the analysis code + }; +} +``` + +## Next steps + + + + Learn how to handle authenticated web pages with MCP + + + Build your own MCP server for custom functionality + + + Learn how to test MCP integrations + + + Deploy your MCP-enabled app to production + + + + + + diff --git a/docs/guides/integrating-with-llm.mdx b/docs/guides/integrating-with-llm.mdx new file mode 100644 index 0000000..a801e53 --- /dev/null +++ b/docs/guides/integrating-with-llm.mdx @@ -0,0 +1,385 @@ +--- +title: "Integrating MCP into Your LLM Application" +description: 'Learn how to integrate the Model Context Protocol (MCP) into your LLM-powered applications' +--- + +The Model Context Protocol (MCP) enables seamless integration between LLM applications and various data sources and tools. This guide will walk you through integrating MCP into your own LLM-powered chatbot application. + +## Our Example Chatbot + +For this guide, we'll be working with a hypothetical customer service chatbot for a software company. Our chatbot currently: + +- Uses an LLM API (like Anthropic's Claude API) to generate responses +- Maintains conversation history in memory +- Has basic error handling and retry logic +- Runs as a web service that customers interact with through a REST API + +However, our chatbot faces some limitations: +- It can't access real-time product documentation or knowledge base articles +- It can't look up customer information or ticket history +- It can't perform actions like creating tickets or updating customer records +- It doesn't stay up-to-date with product changes and new features + +By integrating MCP, we'll enhance our chatbot to: +- Access documentation and knowledge base articles as contextual resources +- Look up customer information through a CRM integration +- Create and update support tickets through a ticketing system integration +- Get real-time updates when documentation or product information changes + +Let's get started! + +## Prerequisites + +1. Clone the example MCP servers: +```bash +git clone https://github.com/modelcontextprotocol/example-servers.git +cd example-servers +npm install +``` + +2. Install the MCP SDK in your chatbot project: +```bash +npm install @modelcontextprotocol/sdk +``` + +## Starting Point: Our Basic Chatbot + +Here's our starting chatbot implementation that we'll enhance with MCP: + +```typescript +interface Message { + role: 'user' | 'assistant'; + content: string; +} + +class CustomerServiceBot { + private conversation: Message[] = []; + private llmClient: LLMClient; // Your LLM API client + + constructor(llmClient: LLMClient) { + this.llmClient = llmClient; + } + + async handleMessage(message: string): Promise { + // Add user message to conversation + this.conversation.push({ role: 'user', content: message }); + + // Get LLM response + const response = await this.llmClient.complete({ + messages: this.conversation, + maxTokens: 1000 + }); + + // Add assistant response to conversation + this.conversation.push({ role: 'assistant', content: response }); + + return response; + } +} +``` + +## Step 1: Adding Documentation Context + +First, let's enhance our chatbot to incorporate product documentation. We'll use the example PostgreSQL server which can store and serve our docs. + +```typescript +import { Client } from "@modelcontextprotocol/sdk/client"; +import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio"; +import { + ListResourcesResultSchema, + ReadResourceResultSchema +} from "@modelcontextprotocol/sdk/types"; + +class EnhancedCustomerServiceBot { + private conversation: Message[] = []; + private llmClient: LLMClient; + private mcpClient: Client; + + constructor(llmClient: LLMClient) { + this.llmClient = llmClient; + + // Initialize MCP client + this.mcpClient = new Client({ + name: "customer-service-bot", + version: "1.0.0" + }); + } + + async initialize() { + // Connect to PostgreSQL server for documentation + const transport = new StdioClientTransport({ + command: "./example-servers/postgres/index.js", + args: ["postgres://localhost/docs"] // Your docs database + }); + await this.mcpClient.connect(transport); + } + + async getRelevantDocs(message: string): Promise { + // List available documentation resources + const { resources } = await this.mcpClient.request( + { method: "resources/list" }, + ListResourcesResultSchema + ); + + // Read each documentation resource + const docs = await Promise.all( + resources.map(async (resource) => { + const { contents } = await this.mcpClient.request( + { + method: "resources/read", + params: { uri: resource.uri } + }, + ReadResourceResultSchema + ); + return contents[0].text; + }) + ); + + return docs.join("\n\n"); + } + + async handleMessage(message: string): Promise { + // Get relevant documentation + const docs = await this.getRelevantDocs(message); + + // Build prompt with documentation context + const prompt = ` + Here is relevant documentation about our product: + ${docs} + + Please use this information to help answer the customer's question. + + Customer: ${message} + `; + + // Add user message to conversation + this.conversation.push({ role: 'user', content: message }); + + // Get LLM response with documentation context + const response = await this.llmClient.complete({ + messages: [...this.conversation, { role: 'user', content: prompt }], + maxTokens: 1000 + }); + + // Add assistant response to conversation + this.conversation.push({ role: 'assistant', content: response }); + + return response; + } +} +``` + +## Step 2: Adding Ticket Management + +Now let's add the ability to create and update support tickets. We'll use the example tools server for this: + +```typescript +import { CallToolResultSchema } from "@modelcontextprotocol/sdk/types"; + +interface Ticket { + id: string; + subject: string; + description: string; + status: 'open' | 'closed'; +} + +class EnhancedCustomerServiceBot { + // ... previous code ... + + async createTicket(subject: string, description: string): Promise { + const result = await this.mcpClient.request( + { + method: "tools/call", + params: { + name: "create_ticket", + arguments: { + subject, + description + } + } + }, + CallToolResultSchema + ); + + return result.toolResult as Ticket; + } + + async handleMessage(message: string): Promise { + // Get relevant documentation + const docs = await this.getRelevantDocs(message); + + // Build prompt with documentation context and ticket creation ability + const prompt = ` + Here is relevant documentation about our product: + ${docs} + + You can create support tickets when needed using the createTicket function. + Only create tickets for actual technical issues that need follow-up. + + Customer: ${message} + `; + + // Get LLM response + const response = await this.llmClient.complete({ + messages: [...this.conversation, { role: 'user', content: prompt }], + maxTokens: 1000, + tools: [{ + name: 'createTicket', + description: 'Create a support ticket for technical issues', + parameters: { + subject: 'string', + description: 'string' + } + }] + }); + + // Check if the LLM wants to create a ticket + if (response.toolCalls?.length > 0) { + const call = response.toolCalls[0]; + const ticket = await this.createTicket( + call.arguments.subject, + call.arguments.description + ); + + // Add ticket creation to conversation + this.conversation.push({ + role: 'system', + content: `Created ticket #${ticket.id}: ${ticket.subject}` + }); + } + + // Add messages to conversation + this.conversation.push({ role: 'user', content: message }); + this.conversation.push({ role: 'assistant', content: response.content }); + + return response.content; + } +} +``` + +## Step 3: Real-time Documentation Updates + +Finally, let's make our chatbot aware of documentation changes in real-time: + +```typescript +class EnhancedCustomerServiceBot { + // ... previous code ... + + async initialize() { + // Connect to PostgreSQL server + const transport = new StdioClientTransport({ + command: "./example-servers/postgres/index.js", + args: ["postgres://localhost/docs"] + }); + await this.mcpClient.connect(transport); + + // Subscribe to documentation updates + const { resources } = await this.mcpClient.request( + { method: "resources/list" }, + ListResourcesResultSchema + ); + + for (const resource of resources) { + await this.mcpClient.request( + { + method: "resources/subscribe", + params: { uri: resource.uri } + }, + EmptyResultSchema + ); + } + + // Handle update notifications + this.mcpClient.setNotificationHandler( + ResourceUpdatedNotificationSchema, + async (notification) => { + console.log(`Documentation updated: ${notification.params.uri}`); + // Optionally clear any cached documentation + } + ); + } +} +``` + +## Using the Enhanced Chatbot + +Here's how to use our enhanced chatbot: + +```typescript +const bot = new EnhancedCustomerServiceBot(llmClient); +await bot.initialize(); + +// Example conversation +const response1 = await bot.handleMessage( + "How do I reset my password?" +); +// Bot responds with information from documentation + +const response2 = await bot.handleMessage( + "I can't log in even after resetting my password" +); +// Bot creates a ticket and responds with next steps + +``` + +## Error Handling + +Add robust error handling around MCP operations: + +```typescript +class EnhancedCustomerServiceBot { + // ... previous code ... + + async getRelevantDocs(message: string): Promise { + try { + const { resources } = await this.mcpClient.request( + { method: "resources/list" }, + ListResourcesResultSchema + ); + + const docs = await Promise.all( + resources.map(async (resource) => { + try { + const { contents } = await this.mcpClient.request( + { + method: "resources/read", + params: { uri: resource.uri } + }, + ReadResourceResultSchema + ); + return contents[0].text; + } catch (error) { + console.error(`Failed to read resource ${resource.uri}:`, error); + return ""; // Skip failed resources + } + }) + ); + + return docs.join("\n\n"); + } catch (error) { + console.error("Failed to list resources:", error); + return ""; // Fallback to no documentation + } + } +} +``` + +## Next Steps + +Now that you've enhanced your chatbot with MCP, you can: + +1. Add more integrations: + - Connect to your actual documentation system + - Integrate with your production ticketing system + - Add CRM integration for customer context + +2. Improve the implementation: + - Add better documentation relevance filtering + - Implement more sophisticated prompt engineering + - Add authentication and access control + - Add monitoring and logging + - Implement caching for frequently accessed resources + +3. Consider building custom MCP servers for your specific needs + +The example servers repository includes other servers you can experiment with, and you can build your own servers to expose custom functionality to your chatbot. \ No newline at end of file diff --git a/essentials/code.mdx b/essentials/code.mdx deleted file mode 100644 index d2a462a..0000000 --- a/essentials/code.mdx +++ /dev/null @@ -1,37 +0,0 @@ ---- -title: 'Code Blocks' -description: 'Display inline code and code blocks' -icon: 'code' ---- - -## Basic - -### Inline Code - -To denote a `word` or `phrase` as code, enclose it in backticks (`). - -``` -To denote a `word` or `phrase` as code, enclose it in backticks (`). -``` - -### Code Block - -Use [fenced code blocks](https://www.markdownguide.org/extended-syntax/#fenced-code-blocks) by enclosing code in three backticks and follow the leading ticks with the programming language of your snippet to get syntax highlighting. Optionally, you can also write the name of your code after the programming language. - -```java HelloWorld.java -class HelloWorld { - public static void main(String[] args) { - System.out.println("Hello, World!"); - } -} -``` - -````md -```java HelloWorld.java -class HelloWorld { - public static void main(String[] args) { - System.out.println("Hello, World!"); - } -} -``` -```` diff --git a/essentials/images.mdx b/essentials/images.mdx deleted file mode 100644 index 60ad42d..0000000 --- a/essentials/images.mdx +++ /dev/null @@ -1,59 +0,0 @@ ---- -title: 'Images and Embeds' -description: 'Add image, video, and other HTML elements' -icon: 'image' ---- - - - -## Image - -### Using Markdown - -The [markdown syntax](https://www.markdownguide.org/basic-syntax/#images) lets you add images using the following code - -```md -![title](/path/image.jpg) -``` - -Note that the image file size must be less than 5MB. Otherwise, we recommend hosting on a service like [Cloudinary](https://cloudinary.com/) or [S3](https://aws.amazon.com/s3/). You can then use that URL and embed. - -### Using Embeds - -To get more customizability with images, you can also use [embeds](/writing-content/embed) to add images - -```html - -``` - -## Embeds and HTML elements - - - -
- - - -Mintlify supports [HTML tags in Markdown](https://www.markdownguide.org/basic-syntax/#html). This is helpful if you prefer HTML tags to Markdown syntax, and lets you create documentation with infinite flexibility. - - - -### iFrames - -Loads another HTML page within the document. Most commonly used for embedding videos. - -```html - -``` diff --git a/essentials/markdown.mdx b/essentials/markdown.mdx deleted file mode 100644 index c8ad9c1..0000000 --- a/essentials/markdown.mdx +++ /dev/null @@ -1,88 +0,0 @@ ---- -title: 'Markdown Syntax' -description: 'Text, title, and styling in standard markdown' -icon: 'text-size' ---- - -## Titles - -Best used for section headers. - -```md -## Titles -``` - -### Subtitles - -Best use to subsection headers. - -```md -### Subtitles -``` - - - -Each **title** and **subtitle** creates an anchor and also shows up on the table of contents on the right. - - - -## Text Formatting - -We support most markdown formatting. Simply add `**`, `_`, or `~` around text to format it. - -| Style | How to write it | Result | -| ------------- | ----------------- | --------------- | -| Bold | `**bold**` | **bold** | -| Italic | `_italic_` | _italic_ | -| Strikethrough | `~strikethrough~` | ~strikethrough~ | - -You can combine these. For example, write `**_bold and italic_**` to get **_bold and italic_** text. - -You need to use HTML to write superscript and subscript text. That is, add `` or `` around your text. - -| Text Size | How to write it | Result | -| ----------- | ------------------------ | ---------------------- | -| Superscript | `superscript` | superscript | -| Subscript | `subscript` | subscript | - -## Linking to Pages - -You can add a link by wrapping text in `[]()`. You would write `[link to google](https://google.com)` to [link to google](https://google.com). - -Links to pages in your docs need to be root-relative. Basically, you should include the entire folder path. For example, `[link to text](/writing-content/text)` links to the page "Text" in our components section. - -Relative links like `[link to text](../text)` will open slower because we cannot optimize them as easily. - -## Blockquotes - -### Singleline - -To create a blockquote, add a `>` in front of a paragraph. - -> Dorothy followed her through many of the beautiful rooms in her castle. - -```md -> Dorothy followed her through many of the beautiful rooms in her castle. -``` - -### Multiline - -> Dorothy followed her through many of the beautiful rooms in her castle. -> -> The Witch bade her clean the pots and kettles and sweep the floor and keep the fire fed with wood. - -```md -> Dorothy followed her through many of the beautiful rooms in her castle. -> -> The Witch bade her clean the pots and kettles and sweep the floor and keep the fire fed with wood. -``` - -### LaTeX - -Mintlify supports [LaTeX](https://www.latex-project.org) through the Latex component. - -8 x (vk x H1 - H2) = (0,1) - -```md -8 x (vk x H1 - H2) = (0,1) -``` diff --git a/essentials/navigation.mdx b/essentials/navigation.mdx deleted file mode 100644 index ca44bb6..0000000 --- a/essentials/navigation.mdx +++ /dev/null @@ -1,66 +0,0 @@ ---- -title: 'Navigation' -description: 'The navigation field in mint.json defines the pages that go in the navigation menu' -icon: 'map' ---- - -The navigation menu is the list of links on every website. - -You will likely update `mint.json` every time you add a new page. Pages do not show up automatically. - -## Navigation syntax - -Our navigation syntax is recursive which means you can make nested navigation groups. You don't need to include `.mdx` in page names. - - - -```json Regular Navigation -"navigation": [ - { - "group": "Getting Started", - "pages": ["quickstart"] - } -] -``` - -```json Nested Navigation -"navigation": [ - { - "group": "Getting Started", - "pages": [ - "quickstart", - { - "group": "Nested Reference Pages", - "pages": ["nested-reference-page"] - } - ] - } -] -``` - - - -## Folders - -Simply put your MDX files in folders and update the paths in `mint.json`. - -For example, to have a page at `https://yoursite.com/your-folder/your-page` you would make a folder called `your-folder` containing an MDX file called `your-page.mdx`. - - - -You cannot use `api` for the name of a folder unless you nest it inside another folder. Mintlify uses Next.js which reserves the top-level `api` folder for internal server calls. A folder name such as `api-reference` would be accepted. - - - -```json Navigation With Folder -"navigation": [ - { - "group": "Group Name", - "pages": ["your-folder/your-page"] - } -] -``` - -## Hidden Pages - -MDX files not included in `mint.json` will not show up in the sidebar but are accessible through the search bar and by linking directly to them. diff --git a/essentials/reusable-snippets.mdx b/essentials/reusable-snippets.mdx deleted file mode 100644 index a0a5529..0000000 --- a/essentials/reusable-snippets.mdx +++ /dev/null @@ -1,110 +0,0 @@ ---- -title: Reusable Snippets -description: Reusable, custom snippets to keep content in sync -icon: 'recycle' ---- - -import SnippetIntro from '/snippets/snippet-intro.mdx'; - - - -## Creating a custom snippet - -**Pre-condition**: You must create your snippet file in the `snippets` directory. - - - Any page in the `snippets` directory will be treated as a snippet and will not - be rendered into a standalone page. If you want to create a standalone page - from the snippet, import the snippet into another file and call it as a - component. - - -### Default export - -1. Add content to your snippet file that you want to re-use across multiple - locations. Optionally, you can add variables that can be filled in via props - when you import the snippet. - -```mdx snippets/my-snippet.mdx -Hello world! This is my content I want to reuse across pages. My keyword of the -day is {word}. -``` - - - The content that you want to reuse must be inside the `snippets` directory in - order for the import to work. - - -2. Import the snippet into your destination file. - -```mdx destination-file.mdx ---- -title: My title -description: My Description ---- - -import MySnippet from '/snippets/path/to/my-snippet.mdx'; - -## Header - -Lorem impsum dolor sit amet. - - -``` - -### Reusable variables - -1. Export a variable from your snippet file: - -```mdx snippets/path/to/custom-variables.mdx -export const myName = 'my name'; - -export const myObject = { fruit: 'strawberries' }; -``` - -2. Import the snippet from your destination file and use the variable: - -```mdx destination-file.mdx ---- -title: My title -description: My Description ---- - -import { myName, myObject } from '/snippets/path/to/custom-variables.mdx'; - -Hello, my name is {myName} and I like {myObject.fruit}. -``` - -### Reusable components - -1. Inside your snippet file, create a component that takes in props by exporting - your component in the form of an arrow function. - -```mdx snippets/custom-component.mdx -export const MyComponent = ({ title }) => ( -
-

{title}

-

... snippet content ...

-
-); -``` - - - MDX does not compile inside the body of an arrow function. Stick to HTML - syntax when you can or use a default export if you need to use MDX. - - -2. Import the snippet into your destination file and pass in the props - -```mdx destination-file.mdx ---- -title: My title -description: My Description ---- - -import { MyComponent } from '/snippets/custom-component.mdx'; - -Lorem ipsum dolor sit amet. - - -``` diff --git a/essentials/settings.mdx b/essentials/settings.mdx deleted file mode 100644 index a8c158c..0000000 --- a/essentials/settings.mdx +++ /dev/null @@ -1,318 +0,0 @@ ---- -title: 'Global Settings' -description: 'Mintlify gives you complete control over the look and feel of your documentation using the mint.json file' -icon: 'gear' ---- - -Every Mintlify site needs a `mint.json` file with the core configuration settings. Learn more about the [properties](#properties) below. - -## Properties - - -Name of your project. Used for the global title. - -Example: `mintlify` - - - - - An array of groups with all the pages within that group - - - The name of the group. - - Example: `Settings` - - - - The relative paths to the markdown files that will serve as pages. - - Example: `["customization", "page"]` - - - - - - - - Path to logo image or object with path to "light" and "dark" mode logo images - - - Path to the logo in light mode - - - Path to the logo in dark mode - - - Where clicking on the logo links you to - - - - - - Path to the favicon image - - - - Hex color codes for your global theme - - - The primary color. Used for most often for highlighted content, section - headers, accents, in light mode - - - The primary color for dark mode. Used for most often for highlighted - content, section headers, accents, in dark mode - - - The primary color for important buttons - - - The color of the background in both light and dark mode - - - The hex color code of the background in light mode - - - The hex color code of the background in dark mode - - - - - - - - Array of `name`s and `url`s of links you want to include in the topbar - - - The name of the button. - - Example: `Contact us` - - - The url once you click on the button. Example: `https://mintlify.com/docs` - - - - - - - - - Link shows a button. GitHub shows the repo information at the url provided including the number of GitHub stars. - - - If `link`: What the button links to. - - If `github`: Link to the repository to load GitHub information from. - - - Text inside the button. Only required if `type` is a `link`. - - - - - - - Array of version names. Only use this if you want to show different versions - of docs with a dropdown in the navigation bar. - - - - An array of the anchors, includes the `icon`, `color`, and `url`. - - - The [Font Awesome](https://fontawesome.com/search?q=heart) icon used to feature the anchor. - - Example: `comments` - - - The name of the anchor label. - - Example: `Community` - - - The start of the URL that marks what pages go in the anchor. Generally, this is the name of the folder you put your pages in. - - - The hex color of the anchor icon background. Can also be a gradient if you pass an object with the properties `from` and `to` that are each a hex color. - - - Used if you want to hide an anchor until the correct docs version is selected. - - - Pass `true` if you want to hide the anchor until you directly link someone to docs inside it. - - - One of: "brands", "duotone", "light", "sharp-solid", "solid", or "thin" - - - - - - - Override the default configurations for the top-most anchor. - - - The name of the top-most anchor - - - Font Awesome icon. - - - One of: "brands", "duotone", "light", "sharp-solid", "solid", or "thin" - - - - - - An array of navigational tabs. - - - The name of the tab label. - - - The start of the URL that marks what pages go in the tab. Generally, this - is the name of the folder you put your pages in. - - - - - - Configuration for API settings. Learn more about API pages at [API Components](/api-playground/demo). - - - The base url for all API endpoints. If `baseUrl` is an array, it will enable for multiple base url - options that the user can toggle. - - - - - - The authentication strategy used for all API endpoints. - - - The name of the authentication parameter used in the API playground. - - If method is `basic`, the format should be `[usernameName]:[passwordName]` - - - The default value that's designed to be a prefix for the authentication input field. - - E.g. If an `inputPrefix` of `AuthKey` would inherit the default input result of the authentication field as `AuthKey`. - - - - - - Configurations for the API playground - - - - Whether the playground is showing, hidden, or only displaying the endpoint with no added user interactivity `simple` - - Learn more at the [playground guides](/api-playground/demo) - - - - - - Enabling this flag ensures that key ordering in OpenAPI pages matches the key ordering defined in the OpenAPI file. - - This behavior will soon be enabled by default, at which point this field will be deprecated. - - - - - - - A string or an array of strings of URL(s) or relative path(s) pointing to your - OpenAPI file. - - Examples: - - ```json Absolute - "openapi": "https://example.com/openapi.json" - ``` - ```json Relative - "openapi": "/openapi.json" - ``` - ```json Multiple - "openapi": ["https://example.com/openapi1.json", "/openapi2.json", "/openapi3.json"] - ``` - - - - - - An object of social media accounts where the key:property pair represents the social media platform and the account url. - - Example: - ```json - { - "x": "https://x.com/mintlify", - "website": "https://mintlify.com" - } - ``` - - - One of the following values `website`, `facebook`, `x`, `discord`, `slack`, `github`, `linkedin`, `instagram`, `hacker-news` - - Example: `x` - - - The URL to the social platform. - - Example: `https://x.com/mintlify` - - - - - - Configurations to enable feedback buttons - - - - Enables a button to allow users to suggest edits via pull requests - - - Enables a button to allow users to raise an issue about the documentation - - - - - - Customize the dark mode toggle. - - - Set if you always want to show light or dark mode for new users. When not - set, we default to the same mode as the user's operating system. - - - Set to true to hide the dark/light mode toggle. You can combine `isHidden` with `default` to force your docs to only use light or dark mode. For example: - - - ```json Only Dark Mode - "modeToggle": { - "default": "dark", - "isHidden": true - } - ``` - - ```json Only Light Mode - "modeToggle": { - "default": "light", - "isHidden": true - } - ``` - - - - - - - - - A background image to be displayed behind every page. See example with - [Infisical](https://infisical.com/docs) and [FRPC](https://frpc.io). - diff --git a/introduction.mdx b/introduction.mdx index 2589c0b..ec9c2f4 100644 --- a/introduction.mdx +++ b/introduction.mdx @@ -1,71 +1,142 @@ --- title: Introduction -description: 'Welcome to the home of your new documentation' +description: 'Get started with the Model Context Protocol (MCP)' --- -Hero Light -Hero Dark +The Model Context Protocol (MCP) is an open protocol that enables seamless integration between LLM applications and external data sources and tools. Whether you're building an AI-powered IDE, enhancing a chat interface, or creating custom AI workflows, MCP provides a standardized way to connect LLMs with the context they need. -## Setting up +## Quickstart Guides -The first step to world-class documentation is setting up your editing environments. +Choose the path that best fits your needs: - Get your docs set up locally for easy development + The fastest way to see MCP in action - connect example servers to Claude in minutes - Preview your changes before you push to make sure they're perfect - - - -## Make it yours - -Update your docs to your brand and add valuable content for the best user conversion. - - - - Customize your docs to your company's colors and brands - - - Automatically generate endpoints from an OpenAPI spec + Create a simple MCP server in TypeScript to understand the basics - Build interactive features and designs to guide your users + Create a simple MCP server in Python to understand the basics - Check out our showcase of our favorite documentation + Add MCP support to your TypeScript/JavaScript LLM application + + + Add MCP support to your Python LLM application + +## Explore MCP + +Dive deeper into MCP's core concepts and capabilities: + + + + Understand how MCP connects clients, servers, and LLMs + + + Expose data and content from your servers to LLMs + + + Create reusable prompt templates and workflows + + + Enable LLMs to perform actions through your server + + + Let your servers request completions from LLMs + + + Learn about MCP's communication mechanisms + + + +## Example Use Cases + +See what you can build with MCP: + + + + Connect your documentation, wikis, and internal knowledge bases to LLMs + + + Query databases and analyze results with natural language + + + Build AI-powered development tools with access to local files and git + + + Securely connect enterprise tools and data to AI interfaces + + + +## Security and Best Practices + +MCP is designed with security in mind, but requires careful implementation: + + + Learn about MCP's security model, best practices, and implementation guidelines + + +Want to contribute? Check out our [GitHub repository](https://github.com/modelcontextprotocol) or join our growing community of developers building with MCP. \ No newline at end of file diff --git a/logo/dark.png b/logo/dark.png new file mode 100644 index 0000000..58156d1 Binary files /dev/null and b/logo/dark.png differ diff --git a/logo/dark.svg b/logo/dark.svg index a628378..b5db00b 100644 --- a/logo/dark.svg +++ b/logo/dark.svg @@ -1,55 +1,17 @@ - - - - - - - - - - - - - - - - + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + diff --git a/logo/light.png b/logo/light.png new file mode 100644 index 0000000..3799509 Binary files /dev/null and b/logo/light.png differ diff --git a/logo/light.svg b/logo/light.svg index 582b3b9..0015bd1 100644 --- a/logo/light.svg +++ b/logo/light.svg @@ -1,51 +1,11 @@ - - - - - - - - - - - - - - - - + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + diff --git a/mint.json b/mint.json index 2799bba..6fce8e4 100644 --- a/mint.json +++ b/mint.json @@ -1,19 +1,16 @@ { "$schema": "https://mintlify.com/schema.json", - "name": "Starter Kit", + "name": "Model Context Protocol", "logo": { "dark": "/logo/dark.svg", "light": "/logo/light.svg" }, "favicon": "/favicon.svg", + "theme": "quill", "colors": { - "primary": "#0D9373", - "light": "#07C983", - "dark": "#0D9373", - "anchors": { - "from": "#0D9373", - "to": "#07C983" - } + "primary": "#09090b", + "light": "#FAFAFA", + "dark": "#09090b" }, "topbarLinks": [ { @@ -53,33 +50,62 @@ "group": "Get Started", "pages": [ "introduction", - "quickstart", - "development" + "docs/guides/claude", + "docs/guides/first-server-python", + "docs/guides/first-server-ts", + "docs/guides/integrate-python", + "docs/guides/integrate-ts" ] }, { - "group": "Essentials", + "group": "Concepts", "pages": [ - "essentials/markdown", - "essentials/code", - "essentials/images", - "essentials/settings", - "essentials/navigation", - "essentials/reusable-snippets" + "docs/core/architecture", + "docs/core/resources", + "docs/core/prompts", + "docs/core/tools", + "docs/core/sampling", + "docs/core/transport" ] }, { - "group": "API Documentation", + "group": "API Reference", "pages": [ - "api-reference/introduction" + "api-reference/protocol-overview", + "api-reference/message-types", + "api-reference/error-handling" ] }, { - "group": "Endpoint Examples", + "group": "Server APIs", "pages": [ - "api-reference/endpoint/get", - "api-reference/endpoint/create", - "api-reference/endpoint/delete" + "api-reference/server-api/resource-management", + "api-reference/server-api/tool-implementation", + "api-reference/server-api/event-handling" + ] + }, + { + "group": "Client APIs", + "pages": [ + "api-reference/client-api/connection-management", + "api-reference/client-api/resource-consumption", + "api-reference/client-api/tool-invocation" + ] + }, + { + "group": "TypeScript SDK", + "pages": [ + "api-reference/typescript/class-reference", + "api-reference/typescript/type-definitions", + "api-reference/typescript/examples" + ] + }, + { + "group": "Python SDK", + "pages": [ + "api-reference/python/class-reference", + "api-reference/python/type-hints", + "api-reference/python/examples" ] } ], diff --git a/quickstart.mdx b/quickstart.mdx deleted file mode 100644 index c44cfaa..0000000 --- a/quickstart.mdx +++ /dev/null @@ -1,86 +0,0 @@ ---- -title: 'Quickstart' -description: 'Start building awesome documentation in under 5 minutes' ---- - -## Setup your development - -Learn how to update your docs locally and deploy them to the public. - -### Edit and preview - - - - During the onboarding process, we created a repository on your Github with - your docs content. You can find this repository on our - [dashboard](https://dashboard.mintlify.com). To clone the repository - locally, follow these - [instructions](https://docs.github.com/en/repositories/creating-and-managing-repositories/cloning-a-repository) - in your terminal. - - - Previewing helps you make sure your changes look as intended. We built a - command line interface to render these changes locally. 1. Install the - [Mintlify CLI](https://www.npmjs.com/package/mintlify) to preview the - documentation changes locally with this command: ``` npm i -g mintlify ``` - 2. Run the following command at the root of your documentation (where - `mint.json` is): ``` mintlify dev ``` - - - -### Deploy your changes - - - - - Our Github app automatically deploys your changes to your docs site, so you - don't need to manage deployments yourself. You can find the link to install on - your [dashboard](https://dashboard.mintlify.com). Once the bot has been - successfully installed, there should be a check mark next to the commit hash - of the repo. - - - [Commit and push your changes to - Git](https://docs.github.com/en/get-started/using-git/pushing-commits-to-a-remote-repository#about-git-push) - for your changes to update in your docs site. If you push and don't see that - the Github app successfully deployed your changes, you can also manually - update your docs through our [dashboard](https://dashboard.mintlify.com). - - - - -## Update your docs - -Add content directly in your files with MDX syntax and React components. You can use any of our components, or even build your own. - - - - - Add flair to your docs with personalized branding. - - - - Implement your OpenAPI spec and enable API user interaction. - - - - Draw insights from user interactions with your documentation. - - - - Keep your docs on your own website's subdomain. - - -