# MCP Integration **Status**: ✅ Complete **Phase**: Phase 2 **Last Updated**: December 6, 2025 --- ## Overview MCP (Model Context Protocol) Integration enables RiceCoder to extend its capabilities through external services and custom tools. This guide covers setting up MCP servers, defining custom tools, configuring permissions, and troubleshooting common issues. ## Key Features - **MCP Server Support**: Integrate external services via the Model Context Protocol - **Custom Tool Definition**: Define simple tools in JSON or Markdown without creating an MCP server - **Tool Permissions**: Control which tools agents can access with granular permission rules - **Tool Discovery**: Discover and query available tools with detailed documentation - **Error Handling**: Robust error handling with automatic reconnection and recovery - **Hot-Reload**: Update configurations without restarting RiceCoder ## How to Use ### Basic Setup 1. Create MCP server configuration in `.ricecoder/mcp-servers.yaml` 2. Define custom tools in `.ricecoder/custom-tools.json` or `.ricecoder/custom-tools.md` 3. Set permissions in `.ricecoder/permissions.yaml` 4. Restart RiceCoder or trigger hot-reload ### Discovering Tools List all available tools: ```bash ricecoder tools list ``` Get details about a specific tool: ```bash ricecoder tools info ``` Search for tools by category: ```bash ricecoder tools search --category database ``` ### Using Tools in Agents Tools are automatically available to agents. Agents can invoke tools using: ```rust let result = agent.invoke_tool("tool-id", parameters).await?; ``` ## Configuration ### MCP Server Configuration **File**: `.ricecoder/mcp-servers.yaml` MCP servers are external processes that provide tools via the Model Context Protocol. Each server is defined with connection details and lifecycle management. **Configuration Structure**: ```yaml servers: - id: name: command: args: - - env: : timeout_ms: auto_reconnect: true max_retries: ``` **Fields**: - `id`: Unique identifier for the server (used in tool IDs) - `name`: Display name for the server - `command`: Executable to run (e.g., `uvx`, `node`, `python`) - `args`: Command-line arguments - `env`: Environment variables to set - `timeout_ms`: Timeout for tool execution (default: 5000) - `auto_reconnect`: Automatically reconnect on failure (default: true) - `max_retries`: Maximum reconnection attempts (default: 3) **Example**: ```yaml servers: - id: database-server name: Database Tools command: uvx args: - database-mcp-server@latest env: DB_URL: postgresql://localhost/mydb timeout_ms: 5000 auto_reconnect: true max_retries: 3 ``` ### Custom Tool Configuration Custom tools are defined in JSON or Markdown format without requiring an MCP server. #### JSON Format **File**: `.ricecoder/custom-tools.json` ```json { "tools": [ { "id": "calculate-sum", "name": "Calculate Sum", "description": "Add two numbers together", "category": "math", "parameters": [ { "name": "a", "type": "number", "description": "First number", "required": true }, { "name": "b", "type": "number", "description": "Second number", "required": true } ], "return_type": "number", "handler": "math::sum" } ] } ``` #### Markdown Format **File**: `.ricecoder/custom-tools.md` ```markdown # Custom Tools ## Calculate Sum - **ID**: calculate-sum - **Category**: math - **Description**: Add two numbers together ### Parameters - **a** (number, required): First number - **b** (number, required): Second number ### Returns number ``` **Fields**: - `id`: Unique identifier for the tool - `name`: Display name - `description`: Tool description - `category`: Tool category for organization - `parameters`: Array of parameter definitions - `name`: Parameter name - `type`: Parameter type (string, number, boolean, object, array) - `description`: Parameter description - `required`: Whether parameter is required - `default`: Default value (optional) - `return_type`: Return type of the tool - `handler`: Function name or script path (for custom tools) ### Permission Configuration **File**: `.ricecoder/permissions.yaml` Permissions control which tools agents can access. Permissions are evaluated in order; the first matching rule is applied. **Configuration Structure**: ```yaml permissions: - pattern: level: agent_id: # Optional: per-agent override ``` **Fields**: - `pattern`: Tool ID pattern (supports wildcards: `*` matches any characters) - `level`: Permission level - `allow`: Execute without asking - `ask`: Prompt user before executing - `deny`: Reject execution - `agent_id`: Optional agent ID for per-agent permissions (omit for global) **Permission Levels**: - **allow**: Tool executes immediately without user confirmation - **ask**: System prompts user before executing the tool - **deny**: Tool execution is rejected; agent cannot use the tool **Wildcard Patterns**: - `database-*`: Matches all tools starting with "database-" - `*-read`: Matches all tools ending with "-read" - `*`: Matches all tools - `database-query`: Exact match **Example**: ```yaml permissions: # Global permissions - pattern: "database-*" level: allow - pattern: "api-*" level: ask - pattern: "dangerous-*" level: deny # Per-agent permissions - pattern: "code-analysis-*" level: allow agent_id: code-analyzer - pattern: "file-write-*" level: ask agent_id: code-generator ``` ## Tool Discovery and Querying ### List All Tools ```bash ricecoder tools list ``` Output: ``` Available Tools: database-query (database-server) Description: Execute database queries Category: database Parameters: query (string, required) Returns: object api-call (api-server) Description: Make API calls Category: api Parameters: endpoint (string, required), method (string, optional) Returns: object calculate-sum (custom) Description: Add two numbers Category: math Parameters: a (number, required), b (number, required) Returns: number ``` ### Get Tool Details ```bash ricecoder tools info database-query ``` Output: ``` Tool: database-query Server: database-server Description: Execute database queries Category: database Parameters: - query (string, required): SQL query to execute Returns: object Permissions: allow (global) Examples: ricecoder tools invoke database-query --query "SELECT * FROM users" ``` ### Search Tools ```bash ricecoder tools search --category database ricecoder tools search --server api-server ricecoder tools search --pattern "*-read" ``` ## Error Handling and Recovery ### Common Errors #### Server Connection Failed **Error**: `MCP server 'database-server' failed to connect` **Causes**: - Server process not running - Server executable not found - Network connectivity issue - Server crashed **Solutions**: 1. Check server configuration in `.ricecoder/mcp-servers.yaml` 2. Verify server executable exists and is executable 3. Check environment variables are set correctly 4. Review server logs for errors 5. Restart RiceCoder to trigger reconnection #### Tool Execution Timeout **Error**: `Tool 'database-query' timed out after 5000ms` **Causes**: - Tool execution taking longer than configured timeout - Server unresponsive - Network latency **Solutions**: 1. Increase `timeout_ms` in server configuration 2. Optimize tool implementation 3. Check server performance 4. Verify network connectivity #### Permission Denied **Error**: `Permission denied for tool 'dangerous-operation'` **Causes**: - Tool permission set to "deny" - Wildcard pattern matches tool and denies access - Per-agent permission overrides global permission **Solutions**: 1. Check permission configuration in `.ricecoder/permissions.yaml` 2. Verify wildcard patterns are correct 3. Check per-agent permissions for your agent 4. Update permissions if needed #### Invalid Tool Parameters **Error**: `Invalid parameters for tool 'calculate-sum': missing required parameter 'a'` **Causes**: - Missing required parameter - Parameter type mismatch - Invalid parameter value **Solutions**: 1. Check tool documentation: `ricecoder tools info ` 2. Verify all required parameters are provided 3. Ensure parameter types match expected types 4. Validate parameter values #### Tool Output Validation Failed **Error**: `Tool output validation failed: expected object, got string` **Causes**: - Tool returned unexpected type - Tool implementation error - Schema mismatch **Solutions**: 1. Check tool implementation 2. Verify tool return type in configuration 3. Review tool output format 4. Update tool configuration if needed ### Automatic Recovery RiceCoder automatically handles many error conditions: - **Server Disconnection**: Automatic reconnection with exponential backoff - **Transient Failures**: Automatic retry with configurable max retries - **Timeout**: Automatic interruption and error reporting - **Graceful Degradation**: Continue with available servers if one fails ### Manual Recovery If automatic recovery fails: 1. Check error message and logs 2. Review configuration files 3. Verify server is running 4. Restart RiceCoder: `ricecoder restart` 5. Check troubleshooting section below ## Naming Conflict Resolution When multiple MCP servers provide tools with the same name, RiceCoder uses namespace prefixing to avoid conflicts. ### Conflict Detection If two servers provide a tool with the same ID: ``` database-server: query api-server: query ``` RiceCoder reports a conflict: ``` Tool ID conflict detected: - database-server:query - api-server:query Use fully qualified names to disambiguate: - database-server:query - api-server:query ``` ### Resolution Use fully qualified tool names: ```bash ricecoder tools invoke database-server:query --query "SELECT * FROM users" ricecoder tools invoke api-server:query --endpoint "/users" ``` Or update tool IDs in server configuration to be unique: ```yaml servers: - id: database-server name: Database Tools # ... other config ... tool_prefix: "db" # Tools will be prefixed: db-query - id: api-server name: API Tools # ... other config ... tool_prefix: "api" # Tools will be prefixed: api-query ``` ## Examples ### Example 1: Database Server Integration See [MCP Database Server Example](./MCP-Database-Server-Example.md) ### Example 2: API Service Integration See [MCP API Service Example](./MCP-API-Service-Example.md) ### Example 3: Custom Tools See [MCP Custom Tools Example](./MCP-Custom-Tools-Example.md) ## Troubleshooting ### Server Won't Start **Problem**: MCP server fails to start **Checklist**: - [ ] Server executable exists and is in PATH - [ ] Server has execute permissions - [ ] Environment variables are set correctly - [ ] Server configuration is valid YAML/JSON - [ ] No port conflicts with other services - [ ] Check server logs for error messages **Debug**: ```bash # Test server manually uvx database-mcp-server@latest # Check configuration cat .ricecoder/mcp-servers.yaml # Check logs ricecoder logs --service mcp-server ``` ### Tools Not Discovered **Problem**: Tools from MCP server not appearing in tool list **Checklist**: - [ ] Server is running and connected - [ ] Server configuration is correct - [ ] Tool IDs are unique (no conflicts) - [ ] Permissions allow tool access - [ ] Configuration hot-reload completed **Debug**: ```bash # List tools ricecoder tools list # Check server status ricecoder status --service mcp-server # Reload configuration ricecoder config reload ``` ### Permission Issues **Problem**: Tool execution denied due to permissions **Checklist**: - [ ] Permission configuration is correct - [ ] Wildcard patterns match tool ID - [ ] Per-agent permissions don't override global - [ ] Permission level is not "deny" **Debug**: ```bash # Check tool permissions ricecoder tools info # Check permission configuration cat .ricecoder/permissions.yaml # Test permission ricecoder tools invoke --dry-run ``` ### Performance Issues **Problem**: Tool execution is slow **Checklist**: - [ ] Server is responsive - [ ] Network latency is acceptable - [ ] Tool implementation is efficient - [ ] Timeout is not too short - [ ] No resource contention **Debug**: ```bash # Measure tool execution time time ricecoder tools invoke # Check server performance ricecoder metrics --service mcp-server # Profile tool execution ricecoder profile tools invoke ``` ## See Also - [MCP Server Configuration](./MCP-Server-Configuration.md) - [Custom Tool Definition](./MCP-Custom-Tools.md) - [Permission Configuration](./MCP-Permissions.md) - [MCP Database Server Example](./MCP-Database-Server-Example.md) - [MCP API Service Example](./MCP-API-Service-Example.md) - [Architecture Overview](./Architecture-Overview.md) - [Configuration Guide](./Configuration.md) --- *Last updated: December 6, 2025*