diff --git a/api-reference/client-api/connection-management.mdx b/api-reference/client-api/connection-management.mdx index 7e7a22d..ee99918 100644 --- a/api-reference/client-api/connection-management.mdx +++ b/api-reference/client-api/connection-management.mdx @@ -1,5 +1,5 @@ --- -title: "Connection Management" +title: "Connection management" description: "Learn how to establish and manage MCP client connections" --- diff --git a/api-reference/client-api/resource-consumption.mdx b/api-reference/client-api/resource-consumption.mdx index e00a548..2cac05d 100644 --- a/api-reference/client-api/resource-consumption.mdx +++ b/api-reference/client-api/resource-consumption.mdx @@ -1,5 +1,5 @@ --- -title: "Resource Consumption" +title: "Resource consumption" description: "Learn how to consume resources from MCP servers" --- diff --git a/api-reference/client-api/tool-invocation.mdx b/api-reference/client-api/tool-invocation.mdx index 7d9f700..7c12613 100644 --- a/api-reference/client-api/tool-invocation.mdx +++ b/api-reference/client-api/tool-invocation.mdx @@ -1,5 +1,5 @@ --- -title: "Tool Invocation" +title: "Tool invocation" description: "Learn how to invoke tools through the MCP client API" --- diff --git a/api-reference/error-handling.mdx b/api-reference/error-handling.mdx index 3a8d864..1cf9e9a 100644 --- a/api-reference/error-handling.mdx +++ b/api-reference/error-handling.mdx @@ -1,5 +1,5 @@ --- -title: 'Error Handling' +title: 'Error handling' description: 'How to handle and respond to errors in the Model Context Protocol' --- diff --git a/api-reference/message-types.mdx b/api-reference/message-types.mdx index a5d2387..5690c7b 100644 --- a/api-reference/message-types.mdx +++ b/api-reference/message-types.mdx @@ -1,5 +1,5 @@ --- -title: 'Message Types' +title: 'Message types' description: 'Understanding the different types of messages in the Model Context Protocol' --- diff --git a/api-reference/protocol-overview.mdx b/api-reference/protocol-overview.mdx index a650ab5..b6677e7 100644 --- a/api-reference/protocol-overview.mdx +++ b/api-reference/protocol-overview.mdx @@ -1,5 +1,5 @@ --- -title: "Protocol Overview" +title: "Protocol overview" description: "Learn about the core concepts and architecture of the Model Context Protocol (MCP)" --- @@ -22,10 +22,8 @@ The Model Context Protocol (MCP) is a standardized protocol that enables AI appl -# Core concepts - +## Core concepts MCP defines several key primitives that form the foundation of the protocol: - Data that can be loaded as context for the AI model. Resources have URIs and can contain text or binary data. @@ -41,12 +39,10 @@ MCP defines several key primitives that form the foundation of the protocol: -# Protocol flow - -## Connection and initialization +## Protocol flow +### Connection and initialization When a client connects to an MCP server, they go through the following initialization sequence: - The client establishes a connection to the server using one of the supported transports. @@ -64,10 +60,8 @@ When a client connects to an MCP server, they go through the following initializ After initialization, the client can begin using the server's resources, tools, and other capabilities. -## Transport options - +### Transport options MCP supports multiple transport mechanisms for client-server communication: - - Server process reads from stdin and writes to stdout diff --git a/api-reference/python/class-reference.mdx b/api-reference/python/class-reference.mdx index 1ebd5bc..8887cde 100644 --- a/api-reference/python/class-reference.mdx +++ b/api-reference/python/class-reference.mdx @@ -1,9 +1,9 @@ --- -title: "Python Class Reference" +title: "Python class reference" description: "Complete Python SDK class documentation" --- -## Server Class +## Server class The main class for implementing MCP servers in Python. @@ -25,7 +25,7 @@ Creates a new MCP server instance. ### Decorators -#### Resource Handling +#### Resource handling ##### @server.list_resources() ```python @@ -72,7 +72,7 @@ async def unsubscribe_resource(uri: str) -> None: **Parameters:** - `uri` (str): Resource URI to unsubscribe from -#### Tool Support +#### Tool support ##### @server.list_tools() ```python @@ -99,7 +99,7 @@ async def call_tool(name: str, **kwargs) -> Any: **Returns:** Tool execution result (any JSON-serializable value) -#### Prompt Management +#### Prompt management ##### @server.list_prompts() ```python @@ -128,7 +128,7 @@ async def get_prompt(name: str, arguments: dict) -> PromptResponse: - `messages` (List[Message]): List of prompt messages - `description` (str, optional): Description of the prompt response -### Session Methods +### Session methods Methods available on the server session object: @@ -158,7 +158,7 @@ async def send_log_message( """Sends log messages to clients.""" ``` -## Data Classes +## Data classes ### Resource ```python @@ -204,7 +204,7 @@ class PromptResponse: description: Optional[str] = None ``` -## Example Usage +## Example usage Here's a complete example demonstrating the main features: @@ -263,7 +263,7 @@ if __name__ == "__main__": anyio.run(main) ``` -## Best Practices +## Best practices 1. **Error Handling**: Always implement proper error handling in your server methods: ```python @@ -303,15 +303,15 @@ if __name__ == "__main__": await session.send_resource_updated("example://resource1") ``` -## Transport Options +## Transport options -### stdio Transport +### Stdio transport ```python async with stdio_server() as (read_stream, write_stream): await server.run(read_stream, write_stream) ``` -### SSE Transport +### SSE transport ```python from mcp_python.transport import SSETransport @@ -327,7 +327,7 @@ async def message_endpoint(request: Request): return await transport.handle_message(request) ``` -### WebSocket Transport +### WebSocket transport ```python from mcp_python.transport import WebSocketTransport diff --git a/api-reference/python/type-hints.mdx b/api-reference/python/type-hints.mdx index 1b76006..edb07b5 100644 --- a/api-reference/python/type-hints.mdx +++ b/api-reference/python/type-hints.mdx @@ -1,11 +1,11 @@ --- -title: "Python Type Hints" +title: "Python type hints" description: "Python type system documentation" --- -## Core Types +## Core types -### Resource Types +### Resource types ```python from typing import TypedDict, Optional, Literal, Union, List @@ -38,7 +38,7 @@ class BlobResourceContents(ResourceContents): blob: bytes # Base64 encoded ``` -### Message Types +### Message types ```python class TextContent(TypedDict): @@ -60,7 +60,7 @@ class Message(TypedDict): content: MessageContent ``` -### Tool Types +### Tool types ```python class ToolParameter(TypedDict): @@ -82,7 +82,7 @@ class Tool(TypedDict): inputSchema: ToolSchema ``` -### Prompt Types +### Prompt types ```python class PromptArgument(TypedDict): @@ -103,7 +103,7 @@ class PromptResponse(TypedDict): messages: List[Message] ``` -### Progress Types +### Progress types ```python class Progress(TypedDict): @@ -112,7 +112,7 @@ class Progress(TypedDict): total: Optional[int] ``` -### Logging Types +### Logging types ```python LogLevel = Literal["debug", "info", "warning", "error"] @@ -124,9 +124,9 @@ class LogMessage(TypedDict): data: Any # JSON-serializable value ``` -## Request/Response Types +## Request/Response types -### Resource Requests +### Resource requests ```python class ListResourcesRequest(TypedDict): @@ -155,7 +155,7 @@ class UnsubscribeRequest(TypedDict): uri: str ``` -### Tool Requests +### Tool requests ```python class ListToolsRequest(TypedDict): @@ -177,7 +177,7 @@ class CallToolResponse(TypedDict): toolResult: Any # JSON-serializable value ``` -### Prompt Requests +### Prompt requests ```python class ListPromptsRequest(TypedDict): @@ -195,7 +195,7 @@ class GetPromptRequest(TypedDict): arguments: Optional[dict[str, str]] ``` -## Protocol Types +## Protocol types ### Implementation Info @@ -231,9 +231,9 @@ class ServerCapabilities(TypedDict): tools: Optional[ToolCapabilities] ``` -## Transport Types +## Transport types -### Stream Types +### Stream types ```python class ReadStream(Protocol): @@ -245,7 +245,7 @@ class WriteStream(Protocol): async def write(self, data: bytes) -> None: ... ``` -### Session Types +### Session types ```python class ServerSession(Protocol): @@ -259,9 +259,9 @@ class ServerSession(Protocol): ) -> None: ... ``` -## Usage Examples +## Usage examples -### Type Usage in Handlers +### Type usage in handlers ```python from mcp_python.server import Server @@ -314,7 +314,7 @@ async def get_prompt(name: str, arguments: dict) -> PromptResponse: } ``` -### Type Checking +### Type checking ```python from typing import TypeGuard @@ -330,7 +330,7 @@ def process_message(message: Message) -> str: return f"Image message with type: {content['mimeType']}" ``` -## Additional Notes +## Additional notes - All types are compatible with standard Python type checkers (mypy, pyright) - TypedDict is used extensively to ensure proper structure of JSON-like objects diff --git a/api-reference/server-api/event-handling.mdx b/api-reference/server-api/event-handling.mdx index 674ae4d..f870ebe 100644 --- a/api-reference/server-api/event-handling.mdx +++ b/api-reference/server-api/event-handling.mdx @@ -1,11 +1,11 @@ --- -title: "Event Handling" +title: "Event handling" description: "Handle events and manage state in your MCP server" --- MCP servers process various events including requests, notifications, and connection lifecycle events. This guide explains how to implement event handlers effectively in your server. -## Request handlers +## Request handling Request handlers process incoming requests from clients and must return a response. Each handler is associated with a specific method name. @@ -62,7 +62,7 @@ async def handle_list_tools(request: ListToolsRequest) -> ListToolsResult: ``` -## Notification handlers +## Notification handling Notification handlers process one-way messages that don't require responses. They're useful for handling events like resource updates or logging messages. diff --git a/api-reference/server-api/resource-management.mdx b/api-reference/server-api/resource-management.mdx index 380695a..1bcbf1c 100644 --- a/api-reference/server-api/resource-management.mdx +++ b/api-reference/server-api/resource-management.mdx @@ -1,5 +1,5 @@ --- -title: "Resource Management" +title: "Resource management" description: "How to implement resource management in your MCP server" --- diff --git a/api-reference/server-api/tool-implementation.mdx b/api-reference/server-api/tool-implementation.mdx index 2cb51ed..b98b3c2 100644 --- a/api-reference/server-api/tool-implementation.mdx +++ b/api-reference/server-api/tool-implementation.mdx @@ -1,5 +1,5 @@ --- -title: "Tool Implementation" +title: "Tool implementation" description: "Learn how to implement tools in your MCP server" --- diff --git a/api-reference/typescript/class-reference.mdx b/api-reference/typescript/class-reference.mdx index 2c2bb3f..3f93aad 100644 --- a/api-reference/typescript/class-reference.mdx +++ b/api-reference/typescript/class-reference.mdx @@ -1,9 +1,9 @@ --- -title: "TypeScript Class Reference" +title: "TypeScript class reference" description: "Complete TypeScript SDK class documentation" --- -## Client Classes +## Client classes ### Client @@ -65,7 +65,7 @@ getServerVersion(): Implementation | undefined ``` Returns the server's version information after connection. -### Transport Classes +### Transport classes #### StdioClientTransport ```typescript @@ -103,7 +103,7 @@ import { WebSocketClientTransport } from "@modelcontextprotocol/sdk/client/webso constructor(url: URL) ``` -## Server Classes +## Server classes ### Server @@ -173,7 +173,7 @@ getClientVersion(): Implementation | undefined ``` Returns the client's version information after connection. -### Transport Classes +### Transport classes #### StdioServerTransport ```typescript @@ -197,7 +197,7 @@ constructor(endpoint: string, res: ServerResponse) ## Examples -### Client Implementation +### Client implementation ```typescript import { Client } from "@modelcontextprotocol/sdk/client"; @@ -269,7 +269,7 @@ async function main() { } ``` -### Server Implementation +### Server implementation ```typescript import { Server } from "@modelcontextprotocol/sdk/server"; @@ -363,7 +363,7 @@ async function main() { } ``` -## Best Practices +## Best practices 1. **Error Handling** ```typescript diff --git a/api-reference/typescript/type-definitions.mdx b/api-reference/typescript/type-definitions.mdx index 9b02a44..f028fd3 100644 --- a/api-reference/typescript/type-definitions.mdx +++ b/api-reference/typescript/type-definitions.mdx @@ -1,11 +1,11 @@ --- -title: "TypeScript Type Definitions" +title: "TypeScript type definitions" description: "TypeScript type system documentation" --- -## Core Protocol Types +## Core protocol types -### JSON-RPC Types +### JSON-RPC types ```typescript export const JSONRPC_VERSION = "2.0"; @@ -53,7 +53,7 @@ export type JSONRPCMessage = | JSONRPCError; ``` -### Message Content Types +### Message content types ```typescript /** Text provided to or from an LLM */ @@ -84,7 +84,7 @@ export interface Progress { export type ProgressCallback = (progress: Progress) => void; ``` -### Resource Types +### Resource types ```typescript /** The contents of a specific resource */ @@ -120,7 +120,7 @@ export interface ResourceTemplate { } ``` -### Tool Types +### Tool types ```typescript /** Definition for a tool the client can call */ @@ -134,7 +134,7 @@ export interface Tool { } ``` -### Prompt Types +### Prompt types ```typescript /** Describes an argument that a prompt can accept */ @@ -152,9 +152,9 @@ export interface Prompt { } ``` -## Request/Response Types +## Request/response types -### Resource Requests +### Resource requests ```typescript export interface ListResourcesRequest { @@ -195,7 +195,7 @@ export interface UnsubscribeRequest { } ``` -### Tool Requests +### Tool requests ```typescript export interface ListToolsRequest { @@ -226,7 +226,7 @@ export interface CallToolResult { } ``` -### Prompt Requests +### Prompt requests ```typescript export interface ListPromptsRequest { @@ -255,9 +255,9 @@ export interface GetPromptResult { } ``` -## Protocol Types +## Protocol types -### Implementation Info +### Implementation info ```typescript export interface Implementation { @@ -266,7 +266,7 @@ export interface Implementation { } ``` -### Capability Types +### Capability types ```typescript export interface ResourceCapabilities { @@ -296,7 +296,7 @@ export interface ClientCapabilities { } ``` -### Notification Types +### Notification types ```typescript export interface ResourceUpdatedNotification { @@ -328,7 +328,7 @@ export type ServerNotification = | LogMessageNotification; ``` -## Error Types +## Error types ```typescript export enum ErrorCode { @@ -354,7 +354,7 @@ export class McpError extends Error { } ``` -## Transport Types +## Transport types ```typescript export interface Transport { @@ -373,9 +373,9 @@ export interface StdioServerParameters { } ``` -## Usage Examples +## Usage examples -### Type Guards +### Type guards ```typescript function isTextContent(content: @@ -391,7 +391,7 @@ function isResourceUpdatedNotification( } ``` -### Type Assertions +### Type assertions ```typescript function assertResource(data: unknown): asserts data is Resource { @@ -409,7 +409,7 @@ function assertResource(data: unknown): asserts data is Resource { } ``` -### Using Generics +### Using generics ```typescript async function handleResourceContent( @@ -425,7 +425,7 @@ async function handleResourceContent( } ``` -### Working with Union Types +### Working with union types ```typescript function processMessage(message: SamplingMessage): string { @@ -442,7 +442,7 @@ function processMessage(message: SamplingMessage): string { } ``` -## Type Utilities +## Type utilities ```typescript /** Helper type to extract request params from method name */ diff --git a/docs/concepts/architecture.mdx b/docs/concepts/architecture.mdx index c987d90..63a15ac 100644 --- a/docs/concepts/architecture.mdx +++ b/docs/concepts/architecture.mdx @@ -1,5 +1,5 @@ --- -title: "Core Architecture" +title: "Core architecture" description: "Understand how MCP connects clients, servers, and LLMs" --- @@ -27,7 +27,7 @@ flowchart LR ## Core components -### Protocol Layer +### Protocol layer The protocol layer handles message framing, request/response linking, and high-level communication patterns. Key classes include: @@ -51,7 +51,7 @@ class Protocol { The transport layer handles the actual communication between clients and servers. MCP supports multiple transport mechanisms: -1. **stdio Transport** +1. **Stdio transport** - Uses standard input/output for communication - Ideal for local processes ```typescript @@ -61,7 +61,7 @@ The transport layer handles the actual communication between clients and servers } ``` -2. **WebSocket Transport** +2. **WebSocket transport** - Enables real-time bidirectional communication - Supports remote connections ```typescript @@ -71,7 +71,7 @@ The transport layer handles the actual communication between clients and servers } ``` -3. **SSE Transport** +3. **SSE transport** - Uses Server-Sent Events for server-to-client messages - HTTP POST for client-to-server messages ```typescript @@ -136,7 +136,7 @@ sequenceDiagram 3. Client sends `initialized` notification 4. Normal message exchange begins -### 2. Message Exchange +### 2. Message exchange After initialization, the following patterns are supported: @@ -206,54 +206,54 @@ await server.connect(transport); ### Transport selection -1. **Local Communication** +1. **Local communication** - Use stdio transport for local processes - Efficient for same-machine communication - Simple process management -2. **Remote Communication** +2. **Remote communication** - WebSocket for full-duplex communication - SSE for scenarios requiring HTTP compatibility - Consider security implications -### Message Handling +### Message handling -1. **Request Processing** +1. **Request processing** - Validate inputs thoroughly - Use type-safe schemas - Handle errors gracefully - Implement timeouts -2. **Progress Reporting** +2. **Progress reporting** - Use progress tokens for long operations - Report progress incrementally - Include total progress when known -3. **Error Management** +3. **Error management** - Use appropriate error codes - Include helpful error messages - Clean up resources on errors ## Security considerations -1. **Transport Security** +1. **Transport security** - Use TLS for remote connections - Validate connection origins - Implement authentication when needed -2. **Message Validation** +2. **Message validation** - Validate all incoming messages - Sanitize inputs - Check message size limits - Verify JSON-RPC format -3. **Resource Protection** +3. **Resource protection** - Implement access controls - Validate resource paths - Monitor resource usage - Rate limit requests -4. **Error Handling** +4. **Error handling** - Don't leak sensitive information - Log security-relevant errors - Implement proper cleanup @@ -277,6 +277,4 @@ await server.connect(transport); - 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 + - Load test servers \ No newline at end of file diff --git a/docs/concepts/prompts.mdx b/docs/concepts/prompts.mdx index d553287..d80407a 100644 --- a/docs/concepts/prompts.mdx +++ b/docs/concepts/prompts.mdx @@ -97,7 +97,7 @@ To use a prompt, clients make a `prompts/get` request: Prompts can be dynamic and include: -### Context Integration +### Context integration ```typescript const analyzeLogsPrompt = { diff --git a/docs/concepts/resources.mdx b/docs/concepts/resources.mdx index 517d629..f48f14f 100644 --- a/docs/concepts/resources.mdx +++ b/docs/concepts/resources.mdx @@ -38,7 +38,7 @@ The protocol and path structure is defined by the MCP server implementation. Ser Resources can contain two types of content: -### Text Resources +### Text resources Text resources contain UTF-8 encoded text data. These are suitable for: - Source code diff --git a/docs/concepts/sampling.mdx b/docs/concepts/sampling.mdx index 21f9dbd..d5aeb78 100644 --- a/docs/concepts/sampling.mdx +++ b/docs/concepts/sampling.mdx @@ -141,7 +141,7 @@ When implementing sampling: 9. Test with various model parameters 10. Monitor sampling costs -## Human-in-the-loop controls +## Human in the loop controls Sampling is designed with human oversight in mind: diff --git a/docs/concepts/tools.mdx b/docs/concepts/tools.mdx index 2697e84..557186f 100644 --- a/docs/concepts/tools.mdx +++ b/docs/concepts/tools.mdx @@ -31,13 +31,6 @@ Each tool is defined with the following structure: } ``` -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: diff --git a/docs/concepts/transport.mdx b/docs/concepts/transport.mdx index e9e117c..bc50202 100644 --- a/docs/concepts/transport.mdx +++ b/docs/concepts/transport.mdx @@ -73,7 +73,7 @@ const transport = new WebSocketClientTransport( await client.connect(transport); ``` -### Server-sent events (SSE) +### Server-sent events 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. @@ -256,21 +256,21 @@ Tips for debugging transport issues: Choose the appropriate transport based on your needs: -### Use stdio when: +### Use stdio when - Building command-line tools - Implementing local integrations - Needing simple process communication - Working with shell scripts -### Use WebSocket when: +### Use WebSocket when - Real-time updates are needed - Low latency is required - Bidirectional communication is necessary - Working with web applications -### Use SSE when: +### Use SSE when - Only server-to-client streaming is needed - WebSocket support is limited diff --git a/docs/first-server/python.mdx b/docs/first-server/python.mdx index a551d5f..31fc673 100644 --- a/docs/first-server/python.mdx +++ b/docs/first-server/python.mdx @@ -427,7 +427,7 @@ This guide uses the OpenWeatherMap API. You'll need a free API key from [OpenWea -## Available Transports +## Available transports While this guide uses stdio transport, MCP supports multiple transport options: @@ -445,7 +445,7 @@ transport = SSEServerTransport("/events", response) ## Troubleshooting -### Installation Issues +### Installation issues ```bash # Check Python version python --version @@ -455,14 +455,14 @@ pip uninstall -r requirements.txt pip install -r requirements.txt ``` -### Runtime Errors +### Runtime errors ```bash # Enable debug logging export MCP_LOG_LEVEL=DEBUG python weather_server.py ``` -### Type Checking +### Type checking ```bash # Install mypy pip install mypy @@ -523,7 +523,7 @@ mypy weather_server.py -## Advanced Features +## Advanced features diff --git a/docs/first-server/typescript.mdx b/docs/first-server/typescript.mdx index ecd06d8..0047394 100644 --- a/docs/first-server/typescript.mdx +++ b/docs/first-server/typescript.mdx @@ -562,7 +562,7 @@ This guide uses the OpenWeatherMap API. You'll need a free API key from [OpenWea -## Available Transports +## Available transports While this guide uses stdio transport, MCP supports multiple transport options: @@ -580,7 +580,7 @@ const transport = new SSEServerTransport("/events", response); ## Troubleshooting -### Build Errors +### Build errors ```bash # Check TypeScript version npx tsc --version @@ -590,7 +590,7 @@ rm -rf dist/ npm run build ``` -### Runtime Errors +### Runtime errors Look for detailed error messages in the Claude app logs: ```bash # Launch Claude with logging @@ -600,7 +600,7 @@ open /Applications/Claude.app --stdout ~/Claude.log --stderr ~/Claude.log tail -f ~/Claude.log ``` -### Type Errors +### Type errors ```bash # Check types without building npx tsc --noEmit diff --git a/docs/tools/debugging.mdx b/docs/tools/debugging.mdx new file mode 100644 index 0000000..126630b --- /dev/null +++ b/docs/tools/debugging.mdx @@ -0,0 +1,242 @@ +--- +title: Debugging MCP servers +description: A comprehensive guide to debugging Model Context Protocol (MCP) servers and integrations +--- + +Effective debugging is essential when developing MCP servers or integrating them with applications. This guide covers the debugging tools and approaches available in the MCP ecosystem. + +## Debugging tools overview + +MCP provides several tools for debugging at different levels: + +1. **MCP Inspector** + - Interactive debugging interface + - Direct server testing + - See the [Inspector Guide](docs/tools/inspector) for details + +2. **Claude.app Developer Tools** + - Integration testing + - Log collection + - Chrome DevTools integration + +3. **Server Logging** + - Custom logging implementations + - Error tracking + - Performance monitoring + +## Debugging in Claude.app + +### Checking server status + +The Claude.app interface provides basic server status information: + +1. Click the 🔌 icon to view: + - Connected servers + - Available prompts + - Accessible resources + - Supported tools + +### Enabling logging + +Get detailed logs from Claude.app: + +```bash +# Launch with logging enabled +open /Applications/Claude.app --stdout ~/Claude.log --stderr ~/Claude.log + +# Follow logs in real-time +tail -n 100 -f ~/Claude.log +``` + +The logs capture: +- Server connection events +- Configuration issues +- Runtime errors +- Message exchanges + +### Using Chrome DevTools + +Access Chrome's developer tools for deeper inspection: + +1. Enable DevTools: +```bash +jq '.allowDevTools = true' ~/Library/Application\ Support/Claude/developer_settings.json > tmp.json \ + && mv tmp.json ~/Library/Application\ Support/Claude/developer_settings.json +``` + +2. Open DevTools: `Command-Option-Shift-i` + +Note: You'll see two DevTools windows: +- Main content window +- App title bar window + +Use the Network panel to inspect: +- WebSocket connections +- Server-sent events +- Message payloads +- Connection timing + +## Common issues + +### Environment variables + +MCP servers don't inherit environment variables automatically. Configure them in `claude_desktop_config.json`: + +```json +{ + "myserver": { + "command": "mcp-server-myapp", + "env": { + "HOME": "/Users/username", + "PATH": "/usr/local/bin:/usr/bin:/bin" + } + } +} +``` + +### Server initialization + +Common initialization problems: + +1. **Path Issues** + - Incorrect server executable path + - Missing required files + - Permission problems + +2. **Configuration Errors** + - Invalid JSON syntax + - Missing required fields + - Type mismatches + +3. **Environment Problems** + - Missing environment variables + - Incorrect variable values + - Permission restrictions + +### Connection problems + +When servers fail to connect: + +1. Check Claude.app logs +2. Verify server process is running +3. Test standalone with Inspector +4. Check network connectivity +5. Verify protocol compatibility + +## Implementing logging + +### Server-side logging + +Implement custom logging in your server: + +```typescript +server.setNotificationHandler(LoggingMessageNotificationSchema, (notification) => { + console.log(`[${notification.params.level}] ${notification.params.data}`); +}); +``` + +Important events to log: +- Initialization steps +- Resource access +- Tool execution +- Error conditions +- Performance metrics + +### Client-side logging + +In client applications: + +1. Enable debug logging +2. Monitor network traffic +3. Track message exchanges +4. Record error states + +## Debugging workflow + +### Development cycle + +1. Initial Development + - Use Inspector for basic testing + - Implement core functionality + - Add logging points + +2. Integration Testing + - Test in Claude.app + - Monitor logs + - Check error handling + +3. Production Deployment + - Verify logging + - Monitor performance + - Track errors + +### Testing changes + +To test changes efficiently: + +- **Configuration changes**: Restart Claude.app +- **Server code changes**: Use Command-R to reload +- **Quick iteration**: Use Inspector during development + +## Best practices + +### Logging strategy + +1. **Structured Logging** + - Use consistent formats + - Include context + - Add timestamps + - Track request IDs + +2. **Error Handling** + - Log stack traces + - Include error context + - Track error patterns + - Monitor recovery + +3. **Performance Tracking** + - Log operation timing + - Monitor resource usage + - Track message sizes + - Measure latency + +### Security considerations + +When debugging: + +1. **Sensitive Data** + - Sanitize logs + - Protect credentials + - Mask personal information + +2. **Access Control** + - Verify permissions + - Check authentication + - Monitor access patterns + +## Getting help + +When encountering issues: + +1. **First Steps** + - Check server logs + - Test with Inspector + - Review configuration + - Verify environment + +2. **Support Channels** + - #mcp-sig channel + - GitHub issues + - MCP Asana project + +3. **Providing Information** + - Log excerpts + - Configuration files + - Steps to reproduce + - Environment details + +## Next steps + +- Learn to use the [MCP Inspector](/docs/tools/inspector) +- Review [Protocol Overview](/api-reference/protocol-overview) +- Study [Error Handling](/api-reference/error-handling) \ No newline at end of file diff --git a/docs/tools/inspector.mdx b/docs/tools/inspector.mdx new file mode 100644 index 0000000..d46fe61 --- /dev/null +++ b/docs/tools/inspector.mdx @@ -0,0 +1,232 @@ +--- +title: MCP Inspector +description: In-depth guide to using the MCP Inspector for testing and debugging Model Context Protocol servers +--- + +The [MCP Inspector](https://github.com/modelcontextprotocol/inspector) is an interactive developer tool for testing and debugging MCP servers. While the [Debugging Guide](docs/tools/debugging) covers the Inspector as part of the overall debugging toolkit, this document provides a detailed exploration of the Inspector's features and capabilities. + +## Getting started + +### Installation and basic usage + +The Inspector runs directly through `npx` without requiring installation: + +```bash +npx @modelcontextprotocol/inspector path/to/server.js +``` + +Pass arguments to your server after the path: +```bash +npx @modelcontextprotocol/inspector path/to/server.js arg1 arg2 +``` + +## Interface overview + +The Inspector provides several key panels for interacting with your MCP server: + +### Server info panel +- Displays server name and version +- Shows negotiated protocol version +- Lists supported capabilities +- Indicates connection status + +### Resources browser +- Lists all available resources +- Shows resource metadata (MIME types, descriptions) +- Allows resource content inspection +- Supports subscription testing + +### Prompts panel +- Displays available prompt templates +- Shows prompt arguments and descriptions +- Enables prompt testing with custom arguments +- Previews generated messages + +### Tools panel +- Lists available tools +- Shows tool schemas and descriptions +- Provides input validation +- Displays tool execution results + +## Testing features + +### Resource testing +```typescript +// Example resource URI to test +resource://myapp/data/123 +``` + +1. View resource metadata +2. Inspect content representations +3. Test subscription updates +4. Monitor resource changes + +### Prompt testing + +Test prompts with different arguments: +```json +{ + "temperature": 0.7, + "style": "concise" +} +``` + +1. Validate argument constraints +2. Preview generated messages +3. Test error conditions +4. Check template rendering + +### Tool testing + +Test tool execution with various inputs: +```json +{ + "query": "SELECT * FROM users", + "limit": 10 +} +``` + +1. Validate input schemas +2. Test error handling +3. Monitor execution progress +4. Inspect tool results + +## Advanced usage + +### Message inspector + +The Message inspector panel shows all communication between the client and server: + +1. Request/response pairs +2. Notifications +3. Progress updates +4. Error messages + +This helps debug: +- Protocol conformance +- Message formatting +- Error conditions +- State transitions + +### Subscription testing + +Test resource subscriptions: + +1. Subscribe to resources +2. Monitor update notifications +3. Test unsubscribe behavior +4. Verify update patterns + +### Capability testing + +Verify server capabilities: + +1. Check supported features +2. Test capability negotiation +3. Verify feature availability +4. Monitor initialization flow + +## Best practices + +### Development workflow + +1. Start Development + - Launch Inspector with your server + - Verify basic connectivity + - Check capability negotiation + +2. Iterative testing + - Make server changes + - Restart Inspector + - Test affected features + - Monitor messages + +3. Error testing + - Test invalid inputs + - Check error responses + - Verify error handling + - Test recovery flows + +### Tips and tricks + +1. Keep Inspector Running + - Monitor changes in real-time + - Quick iteration cycle + - Immediate feedback + +2. Use Message Filtering + - Filter by message type + - Focus on specific features + - Debug targeted behaviors + +3. Test Edge Cases + - Invalid resource URIs + - Malformed tool inputs + - Missing prompt arguments + - Concurrent operations + +## Keyboard shortcuts + +The Inspector supports several keyboard shortcuts for efficient testing: + +| Shortcut | Action | +|----------|---------| +| `Cmd/Ctrl + R` | Reload connection | +| `Cmd/Ctrl + K` | Clear message log | +| `Cmd/Ctrl + F` | Filter messages | +| `Cmd/Ctrl + S` | Save message log | + +## Common patterns + +### Development loop + +1. Start server development +2. Launch Inspector +3. Implement feature +4. Test in Inspector +5. Refine implementation +6. Repeat + +### Integration testing + +1. Test basic functionality +2. Verify error handling +3. Check performance +4. Validate protocols +5. Test user flows + +## Next steps + + + + Check out the MCP Inspector source code + + + + Learn about broader debugging strategies + + + + Explore implementation details + + + + Review message specifications + + \ No newline at end of file diff --git a/docs/unused/integrate-python.mdx b/docs/unused/integrate-python.mdx deleted file mode 100644 index 1ca1919..0000000 --- a/docs/unused/integrate-python.mdx +++ /dev/null @@ -1,442 +0,0 @@ ---- -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/servers - cd 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/unused/integrate-ts.mdx b/docs/unused/integrate-ts.mdx deleted file mode 100644 index 45dc832..0000000 --- a/docs/unused/integrate-ts.mdx +++ /dev/null @@ -1,885 +0,0 @@ ---- -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/servers - cd 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/favicon.svg b/favicon.svg index 03d9f85..9cd24df 100644 --- a/favicon.svg +++ b/favicon.svg @@ -1,12 +1,12 @@ - + - - - + + + - + \ No newline at end of file diff --git a/images/checks-passed.png b/images/checks-passed.png deleted file mode 100644 index 3303c77..0000000 Binary files a/images/checks-passed.png and /dev/null differ diff --git a/introduction.mdx b/introduction.mdx index 5783886..374247c 100644 --- a/introduction.mdx +++ b/introduction.mdx @@ -18,14 +18,14 @@ Choose the path that best fits your needs: The fastest way to see MCP in action - connect example servers to Claude Desktop Create a simple MCP server in Python to understand the basics @@ -33,6 +33,26 @@ Choose the path that best fits your needs: +## Development tools + +Essential tools for building and debugging MCP servers: + + + + Learn how to effectively debug MCP servers and integrations + + + Test and inspect your MCP servers with our interactive debugging tool + + + ## Explore MCP Dive deeper into MCP's core concepts and capabilities: diff --git a/mint.json b/mint.json index 3f2df25..a478a0a 100644 --- a/mint.json +++ b/mint.json @@ -21,10 +21,6 @@ { "name": "API Reference", "url": "api-reference" - }, - { - "name": "Specification", - "url": "specification" } ], "anchors": [ @@ -53,6 +49,10 @@ "group": "Your First MCP Server", "pages": ["docs/first-server/python", "docs/first-server/typescript"] }, + { + "group": "Development Tools", + "pages": ["docs/tools/debugging", "docs/tools/inspector"] + }, { "group": "Concepts", "pages": [ @@ -101,22 +101,6 @@ "api-reference/typescript/class-reference", "api-reference/typescript/type-definitions" ] - }, - { - "group": "Specification", - "pages": [ - "specification/overview", - "specification/jsonrpc", - "specification/lifecycle", - "specification/prompts", - "specification/resources", - "specification/cancellation", - "specification/logging", - "specification/tools", - "specification/completion", - "specification/sampling", - "specification/roots" - ] } ], "footerSocials": { diff --git a/quickstart.mdx b/quickstart.mdx index 99d2da2..95fe29b 100644 --- a/quickstart.mdx +++ b/quickstart.mdx @@ -136,9 +136,11 @@ brew install node git sqlite3 Open your Claude Desktop App configuration: ```bash + # Requires VSCode to be installed to use the 'code' command code ~/Library/Application\ Support/Claude/claude_desktop_config.json ``` + Add this configuration (replace YOUR_USERNAME with your actual username): ```json diff --git a/specification/cancellation.mdx b/specification/cancellation.mdx deleted file mode 100644 index 7a57dd5..0000000 --- a/specification/cancellation.mdx +++ /dev/null @@ -1,67 +0,0 @@ ---- -title: Cancellation ---- - -MCP supports request cancellation through a dedicated notification message. This allows either party to signal that they are no longer interested in the result of an in-flight request. - -## Cancellation Protocol - -When a party wants to cancel a request, they send a "cancelled" notification containing the ID of the request they wish to cancel: - -For example, initiating a request: - -```json -{ - "jsonrpc": "2.0", - "id": "abc123", - "method": "resources/read", - "params": { - "uri": "example://large-file" - } -} -``` - -… then some time later, cancelling that request: - -```json -{ - "jsonrpc": "2.0", - "method": "notifications/cancelled", - "params": { - "requestId": "abc123", - "reason": "User interrupted operation" - } -} -``` - -## Handling Cancellation - -Upon receiving a cancellation notification, the receiver SHOULD: - -1. Stop any processing related to the cancelled request -2. Free any resources associated with that request -3. Not send a response for the cancelled request (even if already computed) - -However, due to race conditions and message latency: - -- The notification may arrive after processing is complete -- A response may already be in transit when cancellation is received -- Multiple cancellation notifications for the same request ID may be received - -## Special Cases - -### Initialize Request - -The client MUST NOT attempt to cancel its `initialize` request. Cancelling initialization leaves the protocol in an undefined state. - -### Long-Running Operations - -For long-running operations that support progress notifications, progress notifications SHOULD stop being sent after receiving cancellation. - -## Best Practices - -1. Implement cancellation handlers for all long-running operations -2. Free resources promptly when receiving cancellation -3. Make cancellation handling idempotent -4. Include meaningful reason strings to aid debugging -5. Log cancellations appropriately for troubleshooting \ No newline at end of file diff --git a/specification/completion.mdx b/specification/completion.mdx deleted file mode 100644 index 3d765d1..0000000 --- a/specification/completion.mdx +++ /dev/null @@ -1,188 +0,0 @@ ---- -title: Argument Completion ---- -Argument Completion enables servers to provide argument completion for prompt and resource URI arguments. Clients can request completion options for specific arguments, and servers can return ranked suggestions. This allows clients to build rich user interfaces with intelligent argument completion for argument values. - -> **_NOTE:_** Argument Completion in MCP is similar to traditional IDE argument completion - it provides contextual suggestions based on available options, rather than AI-powered completion. The server maintains a fixed set of valid values for each argument and returns matching suggestions based on partial input. - -## Capabilities - -Support for argument completion is not indicated by a dedicated capability - servers that expose prompts or resources with arguments implicitly support argument completion for those arguments. Clients may attempt argument completion requests for any prompt or resource argument. - -## Concepts - -### Completion References - -When requesting completions, clients must specify what is being completed using a reference type: - -- `ref/prompt`: References a prompt by name -- `ref/resource`: References a resource by URI - -The reference identifies the context for completion suggestions. - -### Completion Results - -Servers return an array of completion values ranked by relevance, with a maximum of 100 items per response. If more results are available beyond the first 100, servers MUST set `hasMore: true` in the response to indicate that additional results can be retrieved with subsequent requests. The optional `total` field allows servers to specify the complete number of matches available, even if not all are returned in a single response. - -> **_NOTE:_** MCP does not currently support pagination of completion results - clients that need more than the first 100 matches must issue new completion requests with more specific argument values to narrow down the results. - -## Use Cases - -Common use cases for argument completion include: - -### Prompt Argument Completion - -A client requesting completion options for a prompt argument: - -```json -{ - "ref": { - "type": "ref/prompt", - "name": "code_review" - }, - "argument": { - "name": "language", - "value": "py" - } -} -``` - -The server might respond with language suggestions: - -```json -{ - "completion": { - "values": ["python", "pytorch", "pyside", "pyyaml"], - "total": 10, - "hasMore": true - } -} -``` - -### Resource URI Completion - -A client completing a path in a resource URI template: - -```json -{ - "ref": { - "type": "ref/resource", - "uri": "file://{path}" - }, - "argument": { - "name": "path", - "value": "/home/user/doc" - } -} -``` - -The server could respond with matching paths: - -```json -{ - "completion": { - "values": [ - "/home/user/documents", - "/home/user/docker", - "/home/user/downloads" - ], - "hasMore": false - } -} -``` - -## Diagram - -The following diagram visualizes a typical argument completion interaction between client and server: - -```mermaid -sequenceDiagram - participant Client - participant Server - - Note over Client,Server: Client requests completion options - Client->>Server: completion/complete - Server-->>Client: CompleteResult - - Note over Client,Server: Client may request more specific results - opt New completions requested - Client->>Server: completion/complete - Server-->>Client: CompleteResult - end -``` - -## Messages - -This section defines the protocol messages for argument completion in the Model Context Protocol (MCP). - -### Requesting Completions - -#### Request - -To get completion suggestions, the client MUST send a `completion/complete` request. - -Method: `completion/complete` -Params: - - `ref`: A `PromptReference` or `ResourceReference` indicating what is being completed - - `argument`: Object containing: - - `name`: The name of the argument being completed - - `value`: The current value to get completions for - -Example: -```json -{ - "jsonrpc": "2.0", - "id": 1, - "method": "completion/complete", - "params": { - "ref": { - "type": "ref/prompt", - "name": "code_review" - }, - "argument": { - "name": "language", - "value": "py" - } - } -} -``` - -#### Response - -The server MUST respond with a `CompleteResult` containing: - -- `completion`: Object containing: - - `values`: Array of completion suggestions (maximum 100) - - `total`: Optional total number of matches available - - `hasMore`: Optional boolean indicating if additional results exist - -Example: -```json -{ - "jsonrpc": "2.0", - "id": 1, - "result": { - "completion": { - "values": ["python", "pytorch", "pyside"], - "total": 10, - "hasMore": true - } - } -} -``` - -## Error Handling - -Servers MUST return appropriate errors if: -- The referenced prompt or resource does not exist -- The argument name is invalid -- Completion cannot be provided for other reasons - -Clients SHOULD be prepared to handle cases where completion is temporarily unavailable or returns errors. - -## Security Considerations - -Implementations MUST carefully consider: -- Rate limiting completion requests to prevent abuse -- Access control for sensitive completion suggestions -- Validation of completion inputs to prevent injection attacks \ No newline at end of file diff --git a/specification/jsonrpc.mdx b/specification/jsonrpc.mdx deleted file mode 100644 index 0d7f421..0000000 --- a/specification/jsonrpc.mdx +++ /dev/null @@ -1,166 +0,0 @@ ---- -title: Base Protocol ---- - -The Model Context Protocol (MCP) defines a set of JSON-RPC methods for communication between clients and servers in AI-assisted applications. MCP uses [JSON-RPC 2.0](https://www.jsonrpc.org/specification) as its base protocol. - -### Transport - -MCP client **SHOULD** use one of the following transport mechanisms, but are free to use alternative transports where applicable.: - -Standard Input/Output (STDIO) -: Communication occurs through the standard input and output streams. JSON-RPC - messages are sent as individual lines over these streams. Each message is a - complete JSON object serialized as a single line of text, terminated by a - newline character. The client writes requests to the server's standard input - and reads responses from the server's standard output. See [transports](transports.md) for more details. - -HTTP with Server-Sent Events (SSE) -: This transport uses HTTP (1.1 or above) as the underlying protocol. The client sends - requests to the server using standard HTTP POST requests with JSON-RPC - payloads. For server-to-client communication, Server-Sent Events (SSE) are - employed. The server keeps an open connection to the client and sends - messages as SSE events. See [transports](transports.md) for more details. - -### Message Format - -### Progress Notifications - -MCP supports progress tracking for long-running operations through out-of-band notifications. Progress notifications allow the sender of a request to provide updates about the operation's progress. - -To request progress notifications, include a `progressToken` in the request metadata: - -```json -{ - "jsonrpc": "2.0", - "id": 1, - "method": "some_method", - "params": { - "_meta": { - "progressToken": "abc123" - } - } -} -``` - -The receiver MAY then send progress notifications using the same token: - -```json -{ - "jsonrpc": "2.0", - "method": "notifications/progress", - "params": { - "progressToken": "abc123", - "progress": 50, - "total": 100 - } -} -``` - -### Pagination - -Many list operations in MCP support pagination using cursors. The server response will include a `nextCursor` if more results are available: - -```json -{ - "jsonrpc": "2.0", - "id": 1, - "result": { - "resources": [...], - "nextCursor": "next_page_token" - } -} -``` - -Clients can include a `cursor` parameter containing the opaque token from the server, -to obtain the next page starting from the cursor: - -```json -{ - "jsonrpc": "2.0", - "id": 1, - "method": "resources/list", - "params": { - "cursor": "some_opaque_token" - } -} -``` - - -Clients should continue making requests with the provided cursor until no `nextCursor` is returned. - -All messages in MCP **MUST** follow the [JSON-RPC 2.0](https://www.jsonrpc.org/specification) specification. The protocol defines three types of messages: - -1. Requests -2. Responses -3. Notifications - -#### Requests - -Requests are sent from the client to the server or vice versa. They **MUST** include a unique `id` and expect a response. - -#### Responses - -Responses are sent in reply to requests. They **MUST** include the same `id` as the corresponding request. - -#### Notifications - -Notifications are sent from the client to the server or vice versa. They do not expect a response and **MUST NOT** include an `id`. - -### Base Protocol - -The base protocol consists of the following JSON-RPC methods: - -- `initialize`: Sent from the client to the server to initialize the connection. -- `initialized`: Sent from the client to the server after initialization is complete. -- `ping`: Sent by either party to check if the other is still alive. - -Implementations **MUST** support these base protocol methods. - -### Model Context Protocol specific methods - -MCP defines methods based on JSON-RPC that clients and servers implement: - -- [Lifecycle](lifecycle.md) handling -- [Resource](resources.md) management -- [Prompt](prompts.md) handling -- [Tool](tools.md) execution -- [Logging](logging.md) -- [Sampling](sampling.md) - -### Authentication - -Authentication mechanisms are not part of the core MCP specification. Implementations **MAY** provide authentication based on the transport they use.. - -### Versioning - -The MCP version is declared in the `initialize` request and response. Clients and servers **MUST** agree on a compatible protocol version to proceed with communication. - -### Ping Messages - -Either party can send ping messages to check if the other is still alive and responsive: - -```json -{ - "jsonrpc": "2.0", - "id": 1, - "method": "ping" -} -``` - -The receiver MUST respond promptly with an empty result: - -```json -{ - "jsonrpc": "2.0", - "id": 1, - "result": {} -} -``` - -If the receiver fails to respond in a timely manner, the sender MAY disconnect. - -## Specification - -The conical specification can be found at [Model Context Protocol](http://github.com/modelcontextprotocol/spec/tree/main/spec/schema.ts). The specification of the data format -is available in TypeScript (source of truth) and JSON Schema format (generated). \ No newline at end of file diff --git a/specification/lifecycle.mdx b/specification/lifecycle.mdx deleted file mode 100644 index b44a4ba..0000000 --- a/specification/lifecycle.mdx +++ /dev/null @@ -1,202 +0,0 @@ ---- -title: Lifecycle Management ---- - -The Model Context Protocol defines a specific lifecycle for client-server interactions. This lifecycle consists of the following stages: - -Initialization -: The client sends an `initialize` request to the server, initiating the connection. - -Capability Exchange -: The client and server exchange information about their supported features and protocol versions. - -Normal Operation -: After successful initialization, the client and server can freely communicate using the agreed-upon protocol. - -Shutdown -: The connection is terminated, typically initiated by the client when it no longer needs the server's services. - -The initialization sequence in the Model Context Protocol follows these steps: - -```mermaid -sequenceDiagram - participant Client - participant Server - - Client->>Server: initialize request - Note over Client,Server: Includes protocol version, client capabilities - Server->>Client: InitializeResult - Note over Client,Server: Includes protocol version, server capabilities - Client->>Server: initialized notification - Note over Client,Server: Signals completion of initialization - rect rgb(200, 220, 240) - Note over Client,Server: Normal Operation - Client->>Server: Various requests (e.g., list resources, get prompts) - Server->>Client: Responses - Server->>Client: Requests (e.g., LLM sampling) - Client->>Server: Responses - end - Client->>Server: Shutdown (implementation-specific) -``` - -This sequence ensures that both parties are aware of each other's capabilities and agree on the protocol version to be used for further communication. - - -# Details - -## Initialization - -The initialization process **MUST** begin with the client sending an `initialize` request to the server. This request **MUST** include: - -- The *protocol version* supported by the client, as a string -- The client's capabilities -- Information about the client implementation - -Protocol versions are represented as strings in the format `YYYY-MM-DD` (year–month–day, all zero-padded), and can be lexicographically compared—for example, `2024-10-07` is greater than `2024-10-06`. - - - -```typescript -export interface InitializeRequest extends Request { - method: "initialize"; - params: { - protocolVersion: string; - capabilities: ClientCapabilities; - clientInfo: Implementation; - }; -} -``` - -```json -{ - "jsonrpc": "2.0", - "id": 1, - "method": "initialize", - "params": { - "protocolVersion": "2024-10-07", - "capabilities": { - "experimental": {}, - "sampling": {} - }, - "clientInfo": { - "name": "ExampleClient", - "version": "1.0.0" - } - } -} -``` - - - -The server **MUST** respond to the initialize request with an `InitializeResult`. This response **MUST** include: - -- The *protocol version* the server will use -- The server's capabilities -- Information about the server implementation - - - ```typescript - export interface InitializeResult extends Result { - protocolVersion: string; - capabilities: ServerCapabilities; - serverInfo: Implementation; - } - ``` - - ```json - { - "jsonrpc": "2.0", - "id": 1, - "result": { - "protocolVersion": "2024-10-07", - "capabilities": { - "experimental": {}, - "logging": {}, - "prompts": {}, - "resources": { - "subscribe": true - }, - "tools": {} - }, - "serverInfo": { - "name": "ExampleServer", - "version": "1.0.0" - } - } - } - ``` - - -The server may choose a different protocol version than the client has requested. In such cases, it is up to the client whether to proceed with the connection or abort. - -## Capability Exchange - -During the initialization process, both the client and server exchange their capabilities. This allows each party to understand what features and operations are supported by the other. - -The client's capabilities are sent in the `initialize` request: - -```typescript -export interface ClientCapabilities { - experimental?: { [key: string]: object }; - sampling?: {}; -} -``` - -The server's capabilities are sent in the `InitializeResult`: - -```typescript -export interface ServerCapabilities { - experimental?: { [key: string]: object }; - logging?: {}; - prompts?: {}; - resources?: { - subscribe?: boolean; - }; - tools?: {}; -} -``` - -Both parties **SHOULD** respect the capabilities declared by the other and **SHOULD NOT** attempt to use features that are not supported. - -### Capability Descriptions - -Client Capabilities: -- `experimental`: An object containing any experimental, non-standard capabilities supported by the client. -- `sampling`: If present, indicates that the client supports sampling from an LLM. - -Server Capabilities: -- `experimental`: An object containing any experimental, non-standard capabilities supported by the server. -- `logging`: If present, indicates that the server supports controlling logging from client side. -- `prompts`: If present, indicates that the server offers prompt templates. -- `resources`: If present, indicates that the server offers resources to read. The `subscribe` property within this object indicates whether the server supports subscribing to resource updates. -- `tools`: If present, indicates that the server offers tools to call. - -These capabilities allow the client and server to communicate their supported features, enabling them to adapt their behavior accordingly and utilize the full range of supported functionalities during their interaction. - -## Normal Operation - -After successful initialization, the client **MUST** send an `initialized` notification to the server: - -```typescript -export interface InitializedNotification extends Notification { - method: "notifications/initialized"; -} -``` - -Once the server receives this notification, both client and server can begin normal operation. During this phase: - -1. The client **MAY** send requests to the server for various operations such as listing resources, getting prompts, or calling tools. -2. The server **MAY** send requests to the client for operations like sampling from an LLM. -3. Either party **MAY** send notifications to the other as needed. - -Both parties **MUST** be prepared to handle requests and notifications at any time during normal operation. - -## Shutdown - -The Model Context Protocol does not define a specific shutdown procedure. However, implementations **SHOULD** consider the following guidelines: - -1. The client **SHOULD** initiate the shutdown process when it no longer needs the server's services. -2. The server **SHOULD** gracefully terminate any ongoing operations when a shutdown is initiated. -3. Both parties **SHOULD** ensure that any resources are properly released during shutdown. - -Throughout all stages of the lifecycle, both client and server **MUST** adhere to the JSON-RPC 2.0 specification for message formatting and error handling. \ No newline at end of file diff --git a/specification/logging.mdx b/specification/logging.mdx deleted file mode 100644 index 62e56b9..0000000 --- a/specification/logging.mdx +++ /dev/null @@ -1,177 +0,0 @@ ---- -title: Logging -description: "MCP protocol specification for server logging capabilities" ---- - -Logging enables servers to send log messages to clients in a structured way. Clients can control the verbosity of logging by setting the minimum log level they want to receive. Each log message includes a level indicating its severity, an optional logger name for organization, and arbitrary data that can be any JSON-serializable value. - -## Capabilities - -To indicate support for the Logging API, servers MUST include a `logging` capability in their `ServerCapabilities` during initialization. The `logging` capability SHOULD be an empty object: - -```json -{ - "capabilities": { - "logging": {} - } -} -``` - -Clients SHOULD check for this capability before attempting to set the log level. - -## Concepts - -### Log Levels - -MCP defines the following log levels in order of increasing severity: - -- `debug`: Detailed information for debugging -- `info`: General informational messages -- `notice`: Normal but significant events -- `warning`: Warning conditions -- `error`: Error conditions -- `critical`: Critical conditions -- `alert`: Action must be taken immediately -- `emergency`: System is unusable - -These levels correspond to syslog severity levels as defined in [RFC 5424](https://datatracker.ietf.org/doc/html/rfc5424#section-6.2.1). - -### Log Messages - -Each log message contains: -- A severity level -- Optional logger name for categorization -- Arbitrary data payload (any JSON-serializable value) - -## Use Cases - -Common use cases for logging include: - -### Informational Updates - -```json -{ - "level": "info", - "logger": "file_processor", - "data": "Processing file: example.txt" -} -``` - -### Transient errors - -```json -{ - "level": "error", - "logger": "git_clone", - "data": { - "error": "Remote repository temporarily unreachable", - "details": { - "repository": "github.com/example/repo", - "attempt": 2, - "maxAttempts": 3, - "willRetry": true, - "retryIn": "5s" - } - } -} -``` - -## Diagram - -The following diagram visualizes the logging interaction between client and server: - -```mermaid -sequenceDiagram - participant Client - participant Server - - Note over Client,Server: Configure logging - Client->>Server: logging/setLevel (info) - Server-->>Client: EmptyResult - - Note over Client,Server: Server sends log messages - Server--)Client: notifications/message (info) - Server--)Client: notifications/message (error) -``` - -## Messages - -This section defines the protocol messages for logging in the Model Context Protocol (MCP). - -### Setting Log Level - -#### Request - -To configure the minimum log level to receive, the client MUST send a `logging/setLevel` request. - -Method: `logging/setLevel` -Params: - - `level`: The minimum severity level of logs to receive (string, required) - -Example: -```json -{ - "jsonrpc": "2.0", - "id": 1, - "method": "logging/setLevel", - "params": { - "level": "info" - } -} -``` - -#### Response - -The server MUST respond with an empty result if successful: - -```json -{ - "jsonrpc": "2.0", - "id": 1, - "result": {} -} -``` - -### Log Message Notification - -The server sends log messages to the client using the `notifications/message` notification. - -Method: `notifications/message` -Params: - - `level`: The severity level of the message (string, required) - - `logger`: Optional name of the logger (string) - - `data`: The log message data (any JSON-serializable value, required) - -Example: -```json -{ - "jsonrpc": "2.0", - "method": "notifications/message", - "params": { - "level": "error", - "logger": "database", - "data": { - "error": "Connection failed", - "details": { - "host": "localhost", - "port": 5432 - } - } - } -} -``` - -## Error Handling - -Clients MUST be prepared to handle: -- Invalid log levels in setLevel requests -- Missing or malformed log message parameters -- Unexpected data types in log messages - -## Security Considerations - -Implementations MUST carefully consider: -- Sanitizing sensitive information from log messages -- Rate limiting log messages to prevent flooding -- Access control for log configuration -- Validation of log data to prevent injection attacks \ No newline at end of file diff --git a/specification/overview.mdx b/specification/overview.mdx deleted file mode 100644 index 92e5e7a..0000000 --- a/specification/overview.mdx +++ /dev/null @@ -1,208 +0,0 @@ ---- -title: Overview ---- - -The Model Context Protocol (MCP) is an attempt to allow implementors to provide context to various LLM surfaces such as editors/IDEs, [claude.ai](https://claude.ai), etc., in a pluggable way. It separates the concerns of providing context from the LLM loop and its usage within. - -This makes it **much** easier for anyone to script LLM applications for accomplishing their custom workflows, without the application needing to directly offer a large number of integrations. - -# Terminology - -The Model Context Protocol is inspired by Microsoft's [Language Server Protocol](https://microsoft.github.io/language-server-protocol/), with similar concepts: - -* **Server**: a process or service providing context via MCP. -* **Client**: the initiator and client connection to a single MCP server. A message sent through a client is always directed to its one corresponding server. -* **Host**: a process or service which runs any number of MCP clients. [For example, your editor might be a host, claude.ai might be a host, etc.](#example-hosts) -* **Session**: a stateful session established between one client and server. -* **Message**: a message refers to one of the following types of [JSON-RPC](https://www.jsonrpc.org/) object: - * **Request:** a request includes a `method` and `params`, and can be sent by either the server or the client, asking the other for some information or to perform some operation. - * **Response:** a response includes a `result` or an `error`, and is sent *back* after a request, once processing has finished (successfully or unsuccessfully). - * **Notification:** a special type of a request that does not expect a response, notifications are emitted by either the server or client to unilaterally inform the other of an event or state change. -* **Capability**: a feature that the client or server supports. When an MCP connection is initiated, the client and server negotiate the capabilities that they both support, which affects the rest of the interaction. - -## Primitives -On top of the base protocol, MCP introduces these unique primitives: - -* **Resources**: anything that can be loaded as context for an LLM. *Servers* expose a list of resources, identified with [URIs](https://en.wikipedia.org/wiki/Uniform_Resource_Identifier), which the *client* can choose to read or (if supported) subscribe to. Resources can be text or binary data—there are no restrictions on their content. -* **Prompts**: prompts or prompt templates that the *server* can provide to the *client*, which the client can easily surface in the UI (e.g., as some sort of slash command). -* **Tools**: functionality that the *client* can invoke on the *server*, to perform effectful operations. The client can choose to [expose these tools directly to the LLM](https://docs.anthropic.com/en/docs/build-with-claude/tool-use) too, allowing it to decide when and how to use them. -* **Sampling**: *servers* can ask the *client* to sample from the LLM, which allows servers to implement agentic behaviors without having to implement sampling themselves. This also allows the client to combine the sampling request with *all of the other context it has*, making it much more intelligent—while avoiding needlessly exfiltrating information to servers. - -Each primitive can be summarized in the following control hierarchy: - -| Primitive | Control | Description | Example | -|-----------|------------------------|----------------------------------------------------|------------------------------| -| Prompts | User-controlled | Interactive templates invoked by user choice | Slash commands, menu options | -| Resources | Application-controlled | Contextual data attached and managed by the client | File contents, git history | -| Tools | Model-controlled | Functions exposed to the LLM to take actions | API POST requests, file writing | -| Sampling | Server-initiated | LLM completion requests from server to client | Generating AI summaries | - -The communication flow between client and server: - -```mermaid -flowchart LR - server["Server\nScript on local machine, web service, etc."] - host["Host (client)\nEditors, claude.ai, etc."] - - host -->|"resource queries"| server - host -->|"invoke tools"| server - server -->|"sampling"| host - server -.->|"prompt templates"| host - server -.->|"resource contents"| host -``` - -## Control -In addition to basic primitives, MCP offers a set of control flow messages. - -* **Logging:** Anything related to how the server processes logs. -* **Completion**: Supports completion of server arguments on the client side. See - -## Error Codes - -MCP uses standard JSON-RPC error codes as well as protocol-specific codes: - -Standard JSON-RPC error codes: -- `-32700`: Parse error -- `-32600`: Invalid request -- `-32601`: Method not found -- `-32602`: Invalid params -- `-32603`: Internal error - -All error responses MUST include: -- A numeric error code -- A human-readable message -- Optional additional error data - -Example error response: -```json -{ - "jsonrpc": "2.0", - "id": 1, - "error": { - "code": -32602, - "message": "Required parameter missing", - "data": { - "parameter": "uri" - } - } -} -``` -# Use cases -Most use cases are around enabling people to build their own specific workflows and integrations. MCP enables engineers and teams to **tailor AI to their needs.** - -The beauty of the Model Context Protocol is that it's **extremely composable**. You can imagine mixing and matching *any number* of the example servers below with any one of the hosts. Each individual server can be quite simple and limited, but *composed together*, you can get a super-powered AI! - -## Example servers -* **File watcher**: read entire local directories, exposed as resources, and subscribe to changes. The server can provide a tool to write changes back to disk too! -* **Screen watcher**: follow along with the user, taking screenshots automatically, and exposing those as resources. The host can use this to automatically attach screen captures to LLM context. -* **Git integration**: could expose context like Git commit history, but probably *most* useful as a source of tools, like: "commit these changes," "merge this and resolve conflicts," etc. -* **GitHub integration**: read and expose GitHub resources: files, commits, pull requests, issues, etc. Could also expose one or more tools to modify GitHub resources, like "create a PR." -* **Asana integration**: similarly to GitHub—read/write Asana projects, tasks, etc. -* **Slack integration**: read context from Slack channels. Could also look for specially tagged messages, or invocations of [shortcuts](https://api.slack.com/interactivity/shortcuts), as sources of context. Could expose tools to post messages to Slack. -* **Google Workspace integration**: read and write emails, docs, etc. -* **IDEs and editors**: IDEs and editors can be [servers](#example-hosts-clients) as well as hosts! As servers, they can be a rich source of context like: output/status of tests, [ASTs](https://en.wikipedia.org/wiki/Abstract_syntax_tree) and parse trees, and "which files are currently open and being edited?" - -A key design principle of MCP is that it should be *as simple as possible* to implement a server. We want anyone to be able to write, e.g., a local Python script of 100 or fewer lines and get a fully functioning server, with capabilities comparable to any of the above. - -## Example hosts -* **IDEs and editors**: An MCP host inside an IDE or editor could support attaching any number of servers, which can be used to populate an in-editor LLM chat interface, as well as (e.g.) contextualize refactoring. In future, we could also imagine populating editors' command palette with all of the tools that MCP servers have made available. -* **claude.ai**: [Claude.ai](https://claude.ai) can become an MCP host, allowing users to connect any number of MCP servers. Resources from those servers could be automatically made available for attaching to any Project or Chat. Claude could also make use of the tools exposed by MCP servers to implement agentic behaviors, saving artifacts to disk or to web services, etc.! -* **Slack**: [Claude in Slack](https://www.anthropic.com/claude-in-slack) on steroids! Building an MCP host into Slack would open the door to much more complex interactions with LLMs via the platform—both in being able to read context from any number of places (for example, all the servers posited above), as well as being able to *take actions*, from Slack, via the tools that MCP servers expose. - -# Protocol -## Initialization -MCP [sessions](lifecycle) begin with an initialization phase, where the client and server identify each other, and exchange information about their respective [capabilities](lifecycle#capability-descriptions). - -The client can only begin requesting resources and invoking tools on the server, and the server can only begin requesting LLM sampling, after the client has issued the `initialized` notification: - -```mermaid -sequenceDiagram - participant client as Client - participant server as Server - - activate client - client -->>+ server: (connect over transport) - client -->> server: initialize - server -->> client: initialize_response - client --) server: initialized (notification) - - loop while connected - alt client to server - client -->> server: request - server -->> client: response - else - client --) server: notification - else server to client - server -->> client: request - client -->> server: response - else - server --) client: notification - end - end - - deactivate server - deactivate client -``` - -## Transports -An MCP server or client must implement one of the following transports. Different transports require different clients (but each can run within the same *host*). - -### stdio -The client spawns the server process and manages its lifetime, and writes messages to it on the server's stdin. The server writes messages back to the client on its stdout. - -Individual JSON-RPC messages are sent as newline-terminated JSON over the interface. - -Anything the server writes to stderr MAY be captured as logging, but the client is also allowed to ignore it completely. - -### SSE -A client can open a [Server-Sent Events](https://en.wikipedia.org/wiki/Server-sent_events) connection to a server, which the server will use to push all of its requests and responses to the client. - -Upon connection, the server MUST issue a `endpoint` event (which is specific to MCP, not a default SSE event). The `data` associated with an `endpoint` event MUST be a URI for the client to use. The endpoint can be a relative or an absolute URI, but MUST always point to the same server origin. Cross-origin endpoints are not allowed, for security. - -The client MUST issue individual JSON-RPC messages through the endpoint identified by the server, using HTTP POST requests—this allows the server to link these out-of-band messages with the ongoing SSE stream. - -In turn, `message` events on the SSE stream will contain individual JSON-RPC messages from the server. The server MUST NOT send a `message` event until after the `endpoint` event has been issued. - -This sequence diagram shows the MCP initialization flow over SSE, followed by open-ended communication between client and server, until ultimately the client disconnects: - -```mermaid -sequenceDiagram - participant client as MCP Client - participant server as MCP Server - - activate client - client->>+server: new EventSource("https://server/mcp") - server->>client: event: endpoint
data: /session?id=8cfc516c-… - - client-->>server: POST https://server/session?id=…
{InitializeRequest} - server->>client: event: message
data: {InitializeResponse} - - client--)server: POST https://server/session?id=…
{InitializedNotification} - - loop client requests and responses - client--)server: POST https://server/session?id=…
{…} - end - - loop server requests and responses - server-)client: event: message
data: {…} - end - - client -x server: EventSource.close() - - deactivate server - deactivate client -``` - -## Security and T&S considerations -This model, while making meaningful changes to productivity and product experience, is effectively a form of arbitrary data access and arbitrary code execution. - -**Every interaction between MCP host and server will need informed user consent.** For example: - -* Servers must only expose user data as [resources](resources) with the user's explicit consent. Hosts must not transmit that data elsewhere without the user's explicit consent. -* Hosts must not invoke tools on servers without the user's explicit consent, and understanding of what the tool will do. -* When a server initiates [sampling](sampling) via a host, the user must have control over: - * *Whether* sampling even occurs. (They may not want to be charged!) - * What the prompt that will actually be sampled is. - * *What the server sees* of the completion when sampling finishes. - -This latter point is why the sampling primitives do not permit MCP servers to see the whole prompt—instead, the host remains in control, and can censor or modify it at will. \ No newline at end of file diff --git a/specification/prompts.mdx b/specification/prompts.mdx deleted file mode 100644 index 6c744c3..0000000 --- a/specification/prompts.mdx +++ /dev/null @@ -1,299 +0,0 @@ ---- -title: Prompts ---- - -Prompts enable servers to provide templated conversations or instructions to clients in a structured way, specifically for interacting with language models. Clients can discover available prompts, retrieve their contents, and optionally provide arguments to customize them. Users may explicitly select prompts via the client UI, or clients can intelligently suggest appropriate prompts based on context. Each prompt is uniquely identified by a name. - -An example of a prompt as a slash command in the Zed editor: -![Slash Command Example](slash-command.png) - -## Capabilities - -To indicate support for the Prompts API, servers MUST include a `prompts` capability in their `ServerCapabilities` during initialization. The `prompts` capability SHOULD be an empty object: - -```json -{ - "capabilities": { - "prompts": {} - } -} -``` - -Clients SHOULD check for this capability before using the Prompts API. - -Servers MAY support notifications for changes to the prompt list. If a server supports this feature, it SHOULD include a `listChanged` property in its `prompts` capability: - -```json -{ - "capabilities": { - "prompts": { - "listChanged": true - } - } -} -``` - -If a server supports this capability, it MAY send `notifications/prompts/list_changed` notifications to inform the client about changes to the available prompts. - -## Concepts - -### Prompt - -A Prompt in the Model Context Protocol (MCP) represents a pre-defined set of messages or instructions that a server can provide to clients. Each Prompt is uniquely identified by a name and may have associated metadata such as a description and required arguments. Prompts can represent various types of interactions, including code reviews, data analysis tasks, or creative writing prompts. - -### Prompt Templates - -Prompt Templates are prompts that can be dynamically generated or customized based on provided arguments. They allow servers to expose a flexible set of prompts that can be tailored to specific use cases. Clients can use these templates by providing the required arguments when retrieving the prompt. - -### Embedded Resource Contents - -Prompts can include embedded resource contents from the MCP server. This allows servers to provide context-rich prompts that incorporate relevant data or files directly into the prompt structure. - -## Use Cases - -Common use cases for prompts include providing standardized instructions for code reviews, data analysis tasks, or creative writing exercises. Here are examples of kinds of prompts that an MCP server could expose: - -### Code Review - -A prompt template for conducting code reviews: - -```json -{ - "name": "code_review", - "description": "Analyze code quality and suggest improvements", - "arguments": [ - { - "name": "language", - "description": "Programming language of the code", - "required": true - }, - { - "name": "code", - "description": "The code snippet to review", - "required": true - } - ] -} -``` - -### Data Analysis - -A prompt for guiding data analysis tasks: - -```json -{ - "name": "data_analysis", - "description": "Provide step-by-step guidance for analyzing a dataset", - "arguments": [ - { - "name": "dataset_description", - "description": "Brief description of the dataset", - "required": true - }, - { - "name": "analysis_goal", - "description": "The main goal of the analysis", - "required": true - } - ] -} -``` - -## Diagram - -The following diagram visualizes a common interaction sequence between -client and server for using prompts: - -```mermaid -sequenceDiagram - participant Client - participant Server - - Note over Client,Server: List prompts - Client->>Server: prompts/list - Server-->>Client: ListPromptsResult - - Note over Client,Server: Client selects a prompt - Client->>Server: prompts/get (Prompt A) - Server-->>Client: GetPromptResult -``` - -## Messages - -This section defines the protocol messages for prompt management in the Model Context Protocol (MCP). - -### Listing Prompts - -The Listing Prompts operation allows clients to discover available prompts on the server. This operation is fundamental to the prompt management process in the Model Context Protocol (MCP). When a client sends a `prompts/list` request, the server responds with a comprehensive list of prompts and prompt templates it can provide. This list enables clients to understand what prompts are available, facilitating subsequent operations such as retrieving specific prompts. - -#### Request - -To retrieve a list of available prompts from the server, the client MUST send a `prompts/list` request. - -* Method: `prompts/list` -* Params: None - -Example request from a client to a server: -```json -{ - "jsonrpc": "2.0", - "id": 1, - "method": "prompts/list" -} -``` - -#### Response - -The server MUST respond with a `ListPromptsResult` containing: - -- `prompts`: An array of `Prompt` objects - -Example: -```json -{ - "jsonrpc": "2.0", - "id": 1, - "result": { - "prompts": [ - { - "name": "code_review", - "description": "Analyze code quality and suggest improvements", - "arguments": [ - { - "name": "language", - "description": "Programming language of the code", - "required": true - }, - { - "name": "code", - "description": "The code snippet to review", - "required": true - } - ] - }, - { - "name": "data_analysis", - "description": "Provide step-by-step guidance for analyzing a dataset", - "arguments": [ - { - "name": "dataset_description", - "description": "Brief description of the dataset", - "required": true - }, - { - "name": "analysis_goal", - "description": "The main goal of the analysis", - "required": true - } - ] - } - ] - } -} -``` - -### Getting a Prompt - -#### Request - -To retrieve the contents of a specific prompt, the client MUST send a `prompts/get` request. - -Method: `prompts/get` -Params: - - `name`: The name of the prompt to retrieve (string, required) - - `arguments`: An optional object containing argument values for prompt templates - -Example: -```json -{ - "jsonrpc": "2.0", - "id": 2, - "method": "prompts/get", - "params": { - "name": "code_review", - "arguments": { - "language": "Python", - "code": "def add(a, b):\n return a + b" - } - } -} -``` - -#### Response - -The server MUST respond with a `GetPromptResult` containing: - -- `description`: An optional string describing the prompt -- `messages`: An array of `PromptMessage` objects representing the prompt content, which may include embedded resource contents - -Example: -```json -{ - "jsonrpc": "2.0", - "id": 2, - "result": { - "description": "A prompt for analyzing code quality", - "messages": [ - { - "role": "user", - "content": { - "type": "text", - "text": "Please review the following Python code snippet and provide feedback on its quality and potential improvements:\n\ndef add(a, b):\n return a + b" - } - }, - { - "role": "assistant", - "content": { - "type": "text", - "text": "Certainly! I'd be happy to review the Python code snippet and provide feedback on its quality and potential improvements. Let's analyze it:" - } - }, - { - "role": "user", - "content": { - "type": "resource", - "resource": { - "uri": "file:///workspace/project/requirements.txt", - "mimeType": "text/plain", - "text": "flask==2.0.1\nnumpy==1.21.0\npandas==1.3.0\n" - } - } - }, - { - "role": "assistant", - "content": { - "type": "text", - "text": "I see you've also provided the contents of the requirements.txt file. This gives us additional context about the project environment. Let's consider these dependencies in our code review as well." - } - } - ] - } -} -``` - -### Prompt List Changed Notification - -If the server supports the `listChanged` capability for prompts, it MAY send a `notifications/prompts/list_changed` notification to inform the client that the list of available prompts has changed. - -#### Notification - -Method: `notifications/prompts/list_changed` -Params: None - -Example: -```json -{ - "jsonrpc": "2.0", - "method": "notifications/prompts/list_changed" -} -``` - -Upon receiving this notification, clients SHOULD request an updated prompt list using the `prompts/list` method to ensure they have the most up-to-date information about available prompts. - -## Error Handling - -Clients MUST be prepared to handle cases where listed prompts become unavailable between listing and retrieval attempts. Servers SHOULD provide appropriate error responses in such scenarios. - -## Security Considerations - -Implementations MUST carefully consider the security implications of exposing prompts, especially when dealing with sensitive data or customizable templates. Proper authentication and authorization mechanisms SHOULD be in place to prevent unauthorized access to prompts. \ No newline at end of file diff --git a/specification/resources.mdx b/specification/resources.mdx deleted file mode 100644 index 4513c5b..0000000 --- a/specification/resources.mdx +++ /dev/null @@ -1,452 +0,0 @@ ---- -title: Resources ---- - - -Resources enable servers to expose arbitrary data to clients in a structured way, specifically for providing context to language models. Clients can discover available resources, read their contents, and optionally subscribe to updates. Users may explicitly attach resources via the client UI, or clients can intelligently select appropriate resources to add to the context. Each resource is uniquely identified by a [URI](https://datatracker.ietf.org/doc/html/rfc3986). - -## Capabilities - -To use resources, the server MUST include the `resources` capability in its `ServerCapabilities` object during the initialization process. The `resources` capability MAY include a `subscribe` field set to `true` if the server supports resource subscriptions. Additionally, the `resources` capability MAY include a `listChanged` field set to `true` if the server supports notifications for changes to the resource list. - -Clients intending to use resources SHOULD check for the presence of the `resources` capability in the server's capabilities before attempting to use any resource-related methods. If the capability is not present, the client MUST NOT attempt to use resource-related methods, as the server does not support them. - -Example of server capabilities with basic resource support: -```json -{ - "capabilities": { - "resources": {} - } -} -``` - -Example of server capabilities including resource support with subscriptions and list change notifications: - -```json -{ - "capabilities": { - "resources": { - "subscribe": true, - "listChanged": true - } - } -} -``` - -In this example, the server supports basic resource operations, subscriptions, and notifications for resource list changes. If `subscribe` is omitted or set to `false`, the server only supports basic resource operations without subscriptions. Similarly, if `listChanged` is omitted or set to `false`, the server does not support notifications for changes to the resource list. - -## Concepts -### Resource - -A Resource in the Model Context Protocol (MCP) represents a discrete unit of data that a server can provide to clients. Each Resource is uniquely identified by a URI and may have associated metadata such as a name and MIME type. Resources can represent various types of data, including files, database records, or application-specific information. - -### Resource Templates -To retrieve available resource templates from the server, the client MUST send a `resources/templates/list` request: - -```json -{ - "jsonrpc": "2.0", - "id": 1, - "method": "resources/templates/list" -} -``` - -The server MUST respond with a list of resource templates: - -```json -{ - "jsonrpc": "2.0", - "id": 1, - "result": { - "resourceTemplates": [ - { - "uriTemplate": "file:///{path}", - "name": "Local File", - "description": "Access local files", - "mimeType": "application/octet-stream" - } - ] - } -} -``` - -Resource templates use URI templates as defined in [RFC 6570](https://datatracker.ietf.org/doc/html/rfc6570) to specify parameterized resource URIs. - -Resource Templates are URI patterns that describe a class of resources that can be dynamically generated or accessed. They use URI templates as defined in [RFC 6570](https://datatracker.ietf.org/doc/html/rfc6570) to specify how clients can construct valid resource URIs. Templates allow servers to expose a potentially large or dynamic set of resources without explicitly listing each one. Clients can use these templates to generate specific resource URIs as needed. - -## Use Cases - -Common usecases for resources include file and folder access to provide code context, but can extend to any other form of model-relevant data. See [list of common URI schemes](#list-of-common-uri-schemas) for more information. Here are examples of kinds of resources that an MCP server could expose: - -### File Access -Resources can be used to expose file access to clients. The server should prefix any file-like resource -with the `file://` scheme, and ensure that the client is aware of how to interpret the file by providing -a correct MIME type. When the client issues a `resources/read` request, the server *MUST* ensure that it -returns the file in the correct encoding for the mime type (e.g., text if possible, or base64 for any binary data). - -```json -{ - "uri": "file:///home/user/documents/example.zip", - "name": "Example Text File", - "mimeType": "application/octet-stream" -} -``` - -### Database Schema - -Resources can also be used to provide specialized structured information. In the following example we are providing a database schema as a custom JSON format that the client is required to understand: - -```json -{ - "uri": "postgres://localhost/some_database/some_table/schema", - "name": "Database schema for some_database.some_table", - "mimeType": "application/json;format=MyApplication::DatabaseSchema" -} -``` - -If the client requests a schema, the server would respond with the custom database schema -JSON, for example - -```json -{ - "schema": "myschema", - "table": "test", - "owner": "a-user", - "definition": "..." -} -``` -## Diagram - -The following diagram visualizes a common intercation sequence between -client and server. This is an example. Clients are free to request any -method at any time. For instance, clients are not required to list resources -before reading them. - -```mermaid -sequenceDiagram - participant Client - participant Server - - Note over Client,Server: List resources - Client->>Server: resources/list - Server-->>Client: ListResourcesResult - - Note over Client,Server: Subscriptions - opt Subscribe to events - Client->>Server: resources/subscribe (Resource A) - Client->>Server: resources/subscribe (Resource Bs - end - Note over Client,Server: Reading a rescoures - Client->>Server: resources/read (Resource A) - Server-->>Client: ReadResourceResult - Note over Client,Server: Notification & Re-reading - opt Subscription notification - Server->>Client: notifications/resources/updated (Resource B) - end - Client->>Server: resources/read (Resource B) - Server-->>Client: ReadResourceResult -``` - -## Messages - -This section defines the protocol messages for resource management in the Model Context Protocol (MCP). Resources are identified by URIs and can represent various types of data exposed by the server. Clients can list available resources, read their contents, and optionally subscribe to updates. - -### Listing Resources -The Listing Resources operation allows clients to discover available resources on the server. This operation is fundamental to the resource management process in the Model Context Protocol (MCP). When a client sends a `resources/list` request, the server responds with a comprehensive list of resources and resource templates it can provide. This list enables clients to understand what data is available, facilitating subsequent operations such as reading resources or subscribing to updates. The response may include both concrete resources (with specific URIs) and resource templates (with URI patterns), giving clients flexibility in accessing and utilizing server-provided data. - -#### Request - -To retrieve a list of available resources from the server, the client MUST send a `resources/list` request. - -* Method: `resources/list` -* Params: None - -Example request from a client to a server: -```json -{ - "jsonrpc": "2.0", - "id": 1, - "method": "resources/list" -} -``` - -### Response - -The server MUST respond with a `ListResourcesResult` containing: - -- `resourceTemplates`: An optional array of `ResourceTemplate` objects -- `resources`: An optional array of `Resource` objects - -The response MAY be empty (i.e., both arrays may be omitted or empty). - -Example: -```json -{ - "jsonrpc": "2.0", - "id": 1, - "result": { - "resourceTemplates": [ - { - "uriTemplate": "file:///{path}", - "name": "Local File", - "description": "Access local files", - "mimeType": "application/octet-stream" - } - ], - "resources": [ - { - "uri": "file:///home/user/document.txt", - "name": "User Document", - "mimeType": "text/plain" - } - ] - } -} -``` - -### Error Handling - -Clients MUST be prepared to handle cases where listed resources become unavailable between listing and access attempts. Servers SHOULD provide appropriate error responses in such scenarios. - -## Reading a Resource - -### Request - -To retrieve the contents of a specific resource, the client MUST send a `resources/read` request. - -Method: `resources/read` -Params: - - `uri`: The URI of the resource to read (string, required) - -Example: -```json -{ - "jsonrpc": "2.0", - "id": 2, - "method": "resources/read", - "params": { - "uri": "file:///home/user/document.txt" - } -} -``` - -### Response - -The server MUST respond with a `ReadResourceResult` containing an array of `ResourceContents` objects. Each object MUST be either a `TextResourceContents` or a `BlobResourceContents`. - -Example (text content): -```json -{ - "jsonrpc": "2.0", - "id": 2, - "result": { - "contents": [ - { - "uri": "file:///home/user/document.txt", - "mimeType": "text/plain", - "text": "This is the content of the document." - } - ] - } -} -``` - -Example (binary content): -```json -{ - "jsonrpc": "2.0", - "id": 2, - "result": { - "contents": [ - { - "uri": "file:///home/user/image.png", - "mimeType": "image/png", - "blob": "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAACklEQVR4nGMAAQAABQABDQottAAAAABJRU5ErkJggg==" - } - ] - } -} -``` - -## Subscriptions - -The Model Context Protocol (MCP) offers an optional subscription mechanism for resources to enable real-time updates and efficient synchronization between clients and servers. This feature allows clients to receive notifications when specific resources they're interested in change, without the need for constant polling. - -Key aspects of resource subscriptions in MCP: - -1. Optional Feature: Subscriptions are not mandatory. Servers MAY support this feature, and clients MAY choose to use it when available. - -2. Real-time Updates: Subscriptions enable clients to receive immediate notifications when resources change, ensuring up-to-date information without delay. - -3. Efficiency: By subscribing only to relevant resources, clients can reduce unnecessary network traffic and processing overhead associated with frequent polling. - -Implementations should carefully consider the implications of supporting subscriptions, including potential increased complexity in server-side resource tracking and the need for robust error handling in case of connection issues or missed updates. - -### Subscribing to Resources -#### Request - -To subscribe to updates for a resource, the client MUST send a `resources/subscribe` request. - -Method: `resources/subscribe` -Params: - - `uri`: The URI of the resource to subscribe to (string, required) - -Example: -```json -{ - "jsonrpc": "2.0", - "id": 3, - "method": "resources/subscribe", - "params": { - "uri": "file:///home/user/document.txt" - } -} -``` - -### Response - -The server MUST respond with an empty result if the subscription is successful, or an error if it fails. - -Example (success): -```json -{ - "jsonrpc": "2.0", - "id": 3, - "result": {} -} -``` - -### Unsubscribing from Resources - -#### Request - -To unsubscribe from updates for a resource, the client MUST send a `resources/unsubscribe` request. - -Method: `resources/unsubscribe` -Params: - - `uri`: The URI of the resource to unsubscribe from (string, required) - -Example: -```json -{ - "jsonrpc": "2.0", - "id": 4, - "method": "resources/unsubscribe", - "params": { - "uri": "file:///home/user/document.txt" - } -} -``` - -#### Response - -The server MUST respond with an empty result if the unsubscription is successful, or an error if it fails. - -Example (success): -```json -{ - "jsonrpc": "2.0", - "id": 4, - "result": {} -} -``` - -### Resource Updated Notification - -When a subscribed resource is updated, the server MUST send a `notifications/resources/updated` notification to the client. - -Method: `notifications/resources/updated` -Params: - - `uri`: The URI of the updated resource (string, required) - -Example: -```json -{ - "jsonrpc": "2.0", - "method": "notifications/resources/updated", - "params": { - "uri": "file:///home/user/document.txt" - } -} -``` - -Servers MUST only send this notification for resources that clients have explicitly subscribed to. - -### Resource List Changed Notification - -If the server supports the `listChanged` capability for resources, it MAY send a `notifications/resources/list_changed` notification to inform the client that the list of available resources has changed. - -#### Notification - -Method: `notifications/resources/list_changed` -Params: None - -Example: -```json -{ - "jsonrpc": "2.0", - "method": "notifications/resources/list_changed" -} -``` - -Upon receiving this notification, clients SHOULD request an updated resource list using the `resources/list` method to ensure they have the most up-to-date information about available resources. - -## Security Considerations - -Implementations MUST carefully consider the security implications of exposing resources, especially when dealing with sensitive data or file systems. Proper authentication and authorization mechanisms SHOULD be in place to prevent unauthorized access to resources. - -## Error Handling - -Servers MUST provide appropriate error responses for all request types when issues occur, such as resource not found, permission denied, or internal server errors. Clients MUST be prepared to handle these error responses gracefully. - -Clients MUST also be prepared for resources to change or become unavailable between listing and reading operations. A resource that was present in a `resources/list` response may no longer exist or may have different contents when a subsequent `resources/read` request is made. Servers SHOULD return appropriate error responses in such cases, and clients SHOULD handle these scenarios gracefully, potentially by refreshing their resource list or retrying the operation. - -Example error response: -```json -{ - "jsonrpc": "2.0", - "id": 5, - "error": { - "code": -32001, - "message": "Resource not found", - "data": { - "uri": "file:///nonexistent/file.txt" - } - } -} -``` - - -## List of common URI schemas -Here are some common URI schemes used in the context of MCP resources: - -https:// -: Used to represent a resource available on the web -: Servers SHOULD use this scheme only when the client can fetch the resource directly -: For other cases, servers SHOULD prefer a different or custom scheme - -file:// -: Used to identify resources that behave like a filesystem -: Does not need to map to an actual physical filesystem -: Servers MAY use XDG MIME types like inode/directory for non-regular files - -s3:// -: Used for Amazon S3 or S3-compatible object storage resources - -gcs:// -: Use for Google Cloud object storage resources - -git:// -: Used to identify Git repositories or specific Git objects - -data: -: Used to embed small pieces of data directly in the URI -: Useful for simple, static resources - -zed:// -: Reserved for integration with the Zed editor. - - zed://prompt-library - : Prompts provided by MCP servers for the Zed prompt library - -If you would like to include a commonly used URI schema in this list, -please open an issue the [MCP Specification Github](https://github.com/modelcontextprotocol/specifications). \ No newline at end of file diff --git a/specification/roots.mdx b/specification/roots.mdx deleted file mode 100644 index a700436..0000000 --- a/specification/roots.mdx +++ /dev/null @@ -1,209 +0,0 @@ ---- -title: Roots -description: "MCP protocol specification for root directory and file access" ---- - -Roots enable clients to provide a list of root directories or files that servers can operate on. This allows servers to understand which parts of the filesystem they have access to and should work with. Servers can request the list of roots from clients that support this capability, and clients can notify servers when the list of available roots changes. - -## Capabilities - -To indicate support for roots, clients MUST include a `roots` capability in their `ClientCapabilities` during initialization: - - - -```json -{ - "capabilities": { - "roots": { } - } -} -``` - -```json -{ - "capabilities": { - "roots": { - "listChanged": true - } - } -} -``` - - -The optional `listChanged` property indicates whether the client will send notifications when the root list changes. - -Servers SHOULD check for this capability before attempting to use any roots functionality. - -## Concepts - -### Root - -A Root in the Model Context Protocol (MCP) represents a directory or file that a server is allowed to operate on. Each Root is uniquely identified by a URI (currently restricted to file:// URIs) and may have an optional human-readable name. Roots define the boundaries of where servers can work within the filesystem. - - -Only URI's starting with **file://** are accepted. - - -## Use Cases - -Common use cases for roots include defining workspace directories, project repositories, or specific files that a server should analyze or modify. Here are some examples: - -### Project Directory - -A root representing a project workspace: - -```json -{ - "uri": "file:///home/user/projects/myproject", - "name": "My Project" -} -``` - -### Multiple Repositories - -Multiple roots for different Git repositories: - -```json -[ - { - "uri": "file:///home/user/repos/frontend", - "name": "Frontend Repository" - }, - { - "uri": "file:///home/user/repos/backend", - "name": "Backend Repository" - } -] -``` - -## Diagram - -The following diagram visualizes the interaction between client and server for roots: - -```mermaid -sequenceDiagram - participant Server - participant Client - - Note over Server,Client: Server requests roots list - Server->>Client: roots/list - Client-->>Server: ListRootsResult - - Note over Server,Client: Client updates roots - opt Roots Changed - Client-)Server: notifications/roots/list_changed - Server->>Client: roots/list - Client-->>Server: ListRootsResult - end -``` - -## Messages - -This section defines the protocol messages for root management in the Model Context Protocol (MCP). - -### Listing Roots - -#### Request - -To retrieve a list of available roots from the client, the server MUST send a `roots/list` request. - -Method: `roots/list` -Params: None - -Example: -```json -{ - "jsonrpc": "2.0", - "id": 1, - "method": "roots/list" -} -``` - -#### Response - -The client MUST respond with a `ListRootsResult` containing: - -- `roots`: An array of `Root` objects - -A `Root` object consists of: -- `uri`: A URI string identifying the root location. Currently only `file://` URIs are supported. This field is required. -- `name`: An optional string providing a human-readable name for the root. - -Example: -```json -{ - "jsonrpc": "2.0", - "id": 1, - "result": { - "roots": [ - { - "uri": "file:///home/user/projects/myproject", - "name": "My Project" - }, - { - "uri": "file:///home/user/repos/backend", - "name": "Backend Repository" - } - ] - } -} -``` - -### Root List Changed Notification - -If the client supports the `listChanged` capability for roots, it MUST send a `notifications/roots/list_changed` notification when the list of available roots changes. - -#### Notification - -Method: `notifications/roots/list_changed` -Params: None - -Example: -```json -{ - "jsonrpc": "2.0", - "method": "notifications/roots/list_changed" -} -``` - -Upon receiving this notification, servers SHOULD request an updated root list using the `roots/list` method to ensure they have the most up-to-date information. - -## Error Handling - -Servers MUST be prepared to handle cases where: -- The client does not support roots -- Listed roots become unavailable -- Access to roots is denied - -The client SHOULD return appropriate error responses in these cases. - -Example error response: -```json -{ - "jsonrpc": "2.0", - "id": 1, - "error": { - "code": -32601, - "message": "Roots not supported", - "data": { - "reason": "Client does not have roots capability" - } - } -} -``` - -## Security Considerations - -Implementations MUST carefully consider: - -- Access control for root directories and files -- Validation of root URIs to prevent path traversal attacks -- Scope limitations to prevent unauthorized access -- Permission checks before exposing roots -- Regular validation that roots remain accessible - -Clients SHOULD: -- Only expose roots that the server has permission to access -- Validate all root URIs before returning them -- Implement proper filesystem permission checks -- Monitor for changes in root accessibility \ No newline at end of file diff --git a/specification/sampling.mdx b/specification/sampling.mdx deleted file mode 100644 index 725ad31..0000000 --- a/specification/sampling.mdx +++ /dev/null @@ -1,236 +0,0 @@ ---- -title: Sampling -description: "MCP protocol specification for language model sampling and text generation" ---- - -Sampling enables servers to request generations from a language model via the client, enabling clients to have control over which model to use and what prompts are accepted. Clients can approve or reject incoming sampling requests, and control permissions around which servers can access which models. Servers can optionally request context from other MCP servers to be included in prompts. Because sampling requests go from server to client, this is the only request type in MCP that flows in this direction. - -## Capabilities - -Clients indicate support for sampling by including a `sampling` capability in their `ClientCapabilities` during initialization. The `sampling` capability SHOULD be an empty object: - -```json -{ - "capabilities": { - "sampling": {} - } -} -``` - -Servers SHOULD check for this capability before attempting to use sampling functionality. - -## Concepts - -### Sampling Request - -A Sampling Request in the Model Context Protocol (MCP) represents a request from a server to generate text from a language model via the client. Each request contains messages to send to the model, optional system prompts, and sampling parameters like temperature and maximum tokens. The client has full discretion over which model to use and whether to approve the request. - -### Message Content - -Message content can be either text or images, allowing for multimodal interactions where supported by the model. Text content is provided directly as strings, while image content must be base64 encoded with an appropriate MIME type. - -### Model Preferences - -Servers can express preferences for model selection using the `ModelPreferences` object. This allows servers to indicate priorities for factors like cost, speed, and intelligence, as well as provide hints for specific models. - -## Use Cases - -Common use cases for sampling include generating responses in chat interfaces, code completion, and content generation. Here are some example sampling scenarios: - -### Chat Response - -A server requesting a chat response with model preferences: - -```json -{ - "messages": [ - { - "role": "user", - "content": { - "type": "text", - "text": "What is the capital of France?" - } - } - ], - "maxTokens": 100, - "temperature": 0.7, - "modelPreferences": { - "hints": [ - { - "name": "claude-3-sonnet" - } - ], - "intelligencePriority": 0.8, - "speedPriority": 0.5 - } -} -``` - -### Image Analysis - -A server requesting analysis of an image: - -```json -{ - "messages": [ - { - "role": "user", - "content": { - "type": "image", - "data": "base64_encoded_image_data", - "mimeType": "image/jpeg" - } - }, - { - "role": "user", - "content": { - "type": "text", - "text": "Describe what you see in this image." - } - } - ], - "maxTokens": 200, - "modelPreferences": { - "hints": [ - { - "name": "claude-3-opus" - }, - { - "name": "claude-3-sonnet" - } - ], - "intelligencePriority": 1.0 - } -} -``` - -## Diagram - -The following diagram visualizes the sampling request flow between -server and client: - -```mermaid -sequenceDiagram - participant Server - participant Client - participant User - participant LLM - - Note over Server,Client: Server requests sampling - Server->>Client: sampling/createMessage - opt User approval - Client->>User: Request approval - User-->>Client: Approve request - end - Client->>LLM: Forward request - LLM-->>Client: Generated response - opt User approval - Client->>User: Review response - User-->>Client: Approve response - end - Client-->>Server: CreateMessageResult -``` - -## Messages - -This section defines the protocol messages for sampling in the Model Context Protocol (MCP). - -### Creating a Message - -#### Request - -To request sampling from an LLM via the client, the server MUST send a `sampling/createMessage` request. - -Method: `sampling/createMessage` -Params: - - `messages`: Array of `SamplingMessage` objects representing the conversation history - - `modelPreferences`: Optional `ModelPreferences` object to guide model selection - - `systemPrompt`: Optional system prompt to use - - `includeContext`: Optional request to include context from MCP servers - - `temperature`: Optional sampling temperature - - `maxTokens`: Maximum tokens to generate - - `stopSequences`: Optional array of sequences that will stop generation - - `metadata`: Optional provider-specific metadata - -Example: -```json -{ - "jsonrpc": "2.0", - "id": 1, - "method": "sampling/createMessage", - "params": { - "messages": [ - { - "role": "user", - "content": { - "type": "text", - "text": "What is the capital of France?" - } - } - ], - "systemPrompt": "You are a helpful assistant.", - "maxTokens": 100, - "temperature": 0.7, - "includeContext": "none", - "modelPreferences": { - "hints": [ - { - "name": "claude-3-sonnet" - }, - { - "name": "claude-3-opus" - } - ], - "intelligencePriority": 0.9, - "speedPriority": 0.6 - } - } -} -``` - -#### Response - -The client MUST respond with a `CreateMessageResult` containing: - -- `role`: The role of the message (always "assistant") -- `content`: The generated content -- `model`: The name of the model used -- `stopReason`: Why generation stopped - -Example: -```json -{ - "jsonrpc": "2.0", - "id": 1, - "result": { - "role": "assistant", - "content": { - "type": "text", - "text": "The capital of France is Paris." - }, - "model": "claude-3-sonnet-20240307", - "stopReason": "endTurn" - } -} -``` - -## Error Handling - -Clients MUST be prepared to handle both user rejection of sampling requests and model API errors. Common error scenarios include: - -- User denies the sampling request -- Model API is unavailable -- Invalid sampling parameters -- Context length exceeded - -The client SHOULD return appropriate error responses to the server in these cases. - -## Security Considerations - -Implementations MUST carefully consider the security implications of allowing servers to request model generations, including: - -- User consent and approval of sampling requests -- Permissions around which servers can access which models -- Content filtering and moderation -- Rate limiting to prevent abuse -- Privacy considerations around included context \ No newline at end of file diff --git a/specification/tools.mdx b/specification/tools.mdx deleted file mode 100644 index bb7ff72..0000000 --- a/specification/tools.mdx +++ /dev/null @@ -1,338 +0,0 @@ ---- -title: Tools ---- - -Tool use enables servers to expose tools (also sometimes called functions) that can be invoked by language models through the client. This allows models to perform actions or retrieve information beyond their training data. Clients can discover available tools, retrieve their specifications, and invoke them on behalf of the model. Each tool is uniquely identified by a name. - -## Capabilities - -To indicate support for the Tools API, servers MUST include a `tools` capability in their `ServerCapabilities` during initialization. The `tools` capability MAY be an empty object: - -```json -{ - "capabilities": { - "tools": {} - } -} -``` - -Clients SHOULD check for this capability before attempting to use any Tools API methods. If the capability is not present, clients SHOULD assume that the server does not support tool functionality. - -Servers MAY support notifications for changes to the tool list. If a server supports this feature, it SHOULD include a `listChanged` property in its `tools` capability: - -```json -{ - "capabilities": { - "tools": { - "listChanged": true - } - } -} -``` - -If a server supports this capability, it MAY send [`notifications/tools/list_changed`](#tool-list-changed-notification) notifications to inform the client about changes to the available tools. -## Concepts - -### Tool - -A Tool in the Model Context Protocol (MCP) represents a function or action that can be invoked by a language model through the client. Each Tool is uniquely identified by a name and has associated metadata such as a description and input schema. Tools can represent various types of actions, including data retrieval, calculations, or external API calls. - -### Tool Specifications - -Tool Specifications describe the structure and expected inputs for each tool. They use JSON Schema to define the input parameters, allowing clients and models to understand how to properly invoke the tools. - -## Use Cases - -Common use cases for tools include data retrieval, performing calculations, or interacting with external services. Here are examples of kinds of tools that an MCP server could expose: - -### Weather Information - -A tool for retrieving current weather information: - -```json -{ - "name": "get_weather", - "description": "Get current weather information for a specific location", - "inputSchema": { - "type": "object", - "properties": { - "location": { - "type": "string", - "description": "City name or zip code" - }, - "units": { - "type": "string", - "enum": ["metric", "imperial"], - "default": "metric" - } - }, - "required": ["location"] - } -} -``` - -### Database Query - -A tool for querying a database: - -```json -{ - "name": "query_database", - "description": "Execute a SQL query on the database", - "inputSchema": { - "type": "object", - "properties": { - "query": { - "type": "string", - "description": "SQL query to execute" - }, - "database": { - "type": "string", - "enum": ["users", "products", "orders"], - "default": "users" - } - }, - "required": ["query"] - } -} -``` - -## Diagram - -The following diagram visualizes a common interaction sequence between -client, server, and language model for using tools: - -```mermaid -sequenceDiagram - participant Model - participant Client - participant Server - - Note over Client,Server: List tools - Client->>Server: tools/list - Server-->>Client: ListToolsResult - Client->>Model: Available tools - - Note over Model,Client: Model selects tool - Model->>Client: Use get_weather tool - Client->>Server: tools/call (get_weather) - Server-->>Client: CallToolResult - Client->>Model: Tool result - - Note over Model,Client: Model processes result - Model->>Client: Generated response -``` - -## Messages - -This section defines the protocol messages for tool management in the Model Context Protocol (MCP). - -### Listing Tools -The Listing Tools operation allows clients to discover available tools on the server. When a client sends a `tools/list` request, the server responds with a comprehensive list of tools it can provide. This list enables clients to understand what tools are available, facilitating subsequent operations such as tool invocation. - -> **_NOTE:_** Tools can change over time. In such cases, the server may send a [Tool List Changed Notification](#tool-list-changed-notification) to inform the client about updates to the available tools. - -#### Request - -To retrieve a list of available tools from the server, the client MUST send a `tools/list` request. - -* Method: `tools/list` -* Params: None - -Example request from a client to a server: -```json -{ - "jsonrpc": "2.0", - "id": 1, - "method": "tools/list" -} -``` - -#### Response - -The server MUST respond with a `ListToolsResult` containing: - -- `tools`: An array of `Tool` objects - -Example: -```json -{ - "jsonrpc": "2.0", - "id": 1, - "result": { - "tools": [ - { - "name": "get_weather", - "description": "Get current weather information for a specific location", - "inputSchema": { - "type": "object", - "properties": { - "location": { - "type": "string", - "description": "City name or zip code" - }, - "units": { - "type": "string", - "enum": ["metric", "imperial"], - "default": "metric" - } - }, - "required": ["location"] - } - }, - { - "name": "query_database", - "description": "Execute a SQL query on the database", - "inputSchema": { - "type": "object", - "properties": { - "query": { - "type": "string", - "description": "SQL query to execute" - }, - "database": { - "type": "string", - "enum": ["users", "products", "orders"], - "default": "users" - } - }, - "required": ["query"] - } - } - ] - } -} -``` - -### Calling a Tool - -#### Request - -To invoke a specific tool, the client MUST send a `tools/call` request. - -Method: `tools/call` -Params: - - `name`: The name of the tool to call (string, required) - - `arguments`: An object containing the tool's input parameters (object, optional) - -Example: -```json -{ - "jsonrpc": "2.0", - "id": 2, - "method": "tools/call", - "params": { - "name": "get_weather", - "arguments": { - "location": "New York", - "units": "imperial" - } - } -} -``` - -#### Response - -The server MUST respond with a `CallToolResult` containing: - -- `content`: An array of content items that can be text, images, or embedded resources -- `isError`: A boolean indicating whether this result represents an error state - -Example: -```json -{ - "jsonrpc": "2.0", - "id": 2, - "result": { - "content": [{ - "type": "text", - "text": "Current weather in New York:\nTemperature: 72°F\nHumidity: 65%\nConditions: Partly cloudy" - }], - "isError": false - } -} -``` - -### Tool List Changed Notification - -If the server supports the `listChanged` capability for tools, it MAY send a `notifications/tools/list_changed` notification to inform the client that the list of available tools has changed. - -#### Notification - -Method: `notifications/tools/list_changed` -Params: None - -Example: -```json -{ - "jsonrpc": "2.0", - "method": "notifications/tools/list_changed" -} -``` - -Upon receiving this notification, clients SHOULD request an updated tool list using the `tools/list` method to ensure they have the most up-to-date information about available tools. - -## Error Handling - -Error handling for tools follows two distinct paths depending on the type of error: - -1. Protocol-level errors (like unknown tools or invalid parameters) MUST be reported as JSON-RPC error responses -2. Tool execution errors SHOULD be reported inside successful CallToolResult responses - -For protocol-level errors, servers MUST return error responses when: -- An unknown tool is requested -- Invalid arguments are provided -- The server does not support tool calls - -Example protocol error response for invalid parameters: -```json -{ - "jsonrpc": "2.0", - "id": 3, - "error": { - "code": -32602, - "message": "Invalid params", - "data": { - "reason": "Missing required argument: location" - } - } -} -``` - -Example protocol error response for an unknown tool: -```json -{ - "jsonrpc": "2.0", - "id": 4, - "error": { - "code": -32602, - "message": "Invalid params", - "data": { - "reason": "Unknown tool: invalid_tool_name" - } - } -} -``` - -For errors that occur during tool execution (like API failures or invalid data), servers SHOULD return these as part of a successful `CallToolResult`. This allows the LLM to see and potentially handle the error condition: - -```json -{ - "jsonrpc": "2.0", - "id": 5, - "result": { - "toolResult": { - "error": "No search results found for query: 'widgets manufactured in 1972'", - "status": "empty_results" - } - } -} -``` - -## Security Considerations - -Implementations MUST carefully consider the security implications of exposing tools, especially when dealing with sensitive data or external services. Proper authentication and authorization mechanisms SHOULD be in place to prevent unauthorized access to tools. - -Clients SHOULD implement user permission prompts before executing tools, especially for tools that may have side effects or access sensitive information. This allows users to maintain control over the actions performed by the language model. - -Servers SHOULD implement rate limiting and input validation to prevent abuse of tool invocations. \ No newline at end of file diff --git a/style.css b/style.css new file mode 100644 index 0000000..cb4b40c --- /dev/null +++ b/style.css @@ -0,0 +1,15 @@ +.stroke-path { + stroke: black; + stroke-width: 12; + stroke-linecap: round; +} + +@media (prefers-color-scheme: dark) { + .stroke-path { + stroke: white; + } + + #clip0_19_13 rect { + fill: transparent; + } +} \ No newline at end of file