# Model Context Protocol (MCP) Integration\n\n**Status**: ✅ Production-Ready (MCP 0.6.0+, integrated with Claude, compatible with all LLMs)\n\nThe MCP server provides standardized Model Context Protocol integration, allowing external LLMs (Claude, GPT-4, local models) to access provisioning\nplatform capabilities as tools. This enables complex multi-step workflows, tool composition, and integration with existing LLM applications.\n\n## Architecture Overview\n\nThe MCP integration follows the Model Context Protocol specification:\n\n```\n┌──────────────────────────────────────────────────────────────┐\n│ External LLM (Claude, GPT-4, etc.)                           │\n└────────────────────┬─────────────────────────────────────────┘\n                     │\n                     │ Tool Calls (JSON-RPC)\n                     ▼\n┌──────────────────────────────────────────────────────────────┐\n│ MCP Server (provisioning/platform/crates/mcp-server)         │\n│                                                              │\n│ ┌───────────────────────────────────────────────────────┐    │\n│ │ Tool Registry                                         │    │\n│ │ - generate_config(description, schema)                │    │\n│ │ - validate_config(config)                             │    │\n│ │ - search_docs(query)                                  │    │\n│ │ - troubleshoot_deployment(logs)                       │    │\n│ │ - get_schema(name)                                    │    │\n│ │ - check_compliance(config, policy)                    │    │\n│ └───────────────────────────────────────────────────────┘    │\n│                         │                                    │\n│                         ▼                                    │\n│ ┌───────────────────────────────────────────────────────┐    │\n│ │ Implementation Layer                                  │    │\n│ │ - AI Service client (ai-service port 8083)            │    │\n│ │ - Validator client                                    │    │\n│ │ - RAG client (SurrealDB)                              │    │\n│ │ - Schema loader                                       │    │\n│ └───────────────────────────────────────────────────────┘    │\n└──────────────────────────────────────────────────────────────┘\n```\n\n## MCP Server Launch\n\nThe MCP server is started as a stdio-based service:\n\n```\n# Start MCP server (stdio transport)\nprovisioning-mcp-server --config /etc/provisioning/ai.toml\n\n# With debug logging\nRUST_LOG=debug provisioning-mcp-server --config /etc/provisioning/ai.toml\n\n# In Claude Desktop configuration\n~/.claude/claude_desktop_config.json:\n{\n  "mcpServers": {\n    "provisioning": {\n      "command": "provisioning-mcp-server",\n      "args": ["--config", "/etc/provisioning/ai.toml"],\n      "env": {\n        "PROVISIONING_TOKEN": "your-auth-token"\n      }\n    }\n  }\n}\n```\n\n## Available Tools\n\n### 1. Config Generation\n\n**Tool**: `generate_config`\n\nGenerate infrastructure configuration from natural language description.\n\n```\n{\n  "name": "generate_config",\n  "description": "Generate a Nickel infrastructure configuration from a natural language description",\n  "inputSchema": {\n    "type": "object",\n    "properties": {\n      "description": {\n        "type": "string",\n        "description": "Natural language description of desired infrastructure"\n      },\n      "schema": {\n        "type": "string",\n        "description": "Target schema name (e.g., 'database', 'kubernetes', 'network'). Optional."\n      },\n      "format": {\n        "type": "string",\n        "enum": ["nickel", "toml"],\n        "description": "Output format (default: nickel)"\n      }\n    },\n    "required": ["description"]\n  }\n}\n```\n\n**Example Usage**:\n\n```\n# Via MCP client\nmcp-client provisioning generate_config \\n  --description "Production PostgreSQL cluster with encryption and daily backups" \\n  --schema database\n\n# Claude desktop prompt:\n# @provisioning: Generate a production PostgreSQL setup with automated backups\n```\n\n**Response**:\n\n```\n{\n  database = {\n    engine = "postgresql",\n    version = "15.0",\n    \n    instance = {\n      instance_class = "db.r6g.xlarge",\n      allocated_storage_gb = 100,\n      iops = 3000,\n    },\n    \n    security = {\n      encryption_enabled = true,\n      encryption_key_id = "kms://prod-db-key",\n      tls_enabled = true,\n      tls_version = "1.3",\n    },\n    \n    backup = {\n      enabled = true,\n      retention_days = 30,\n      preferred_window = "03:00-04:00",\n      copy_to_region = "us-west-2",\n    },\n    \n    monitoring = {\n      enhanced_monitoring_enabled = true,\n      monitoring_interval_seconds = 60,\n      log_exports = ["postgresql"],\n    },\n  }\n}\n```\n\n### 2. Config Validation\n\n**Tool**: `validate_config`\n\nValidate a Nickel configuration against schemas and policies.\n\n```\n{\n  "name": "validate_config",\n  "description": "Validate a Nickel configuration file",\n  "inputSchema": {\n    "type": "object",\n    "properties": {\n      "config": {\n        "type": "string",\n        "description": "Nickel configuration content or file path"\n      },\n      "schema": {\n        "type": "string",\n        "description": "Schema name to validate against (optional)"\n      },\n      "strict": {\n        "type": "boolean",\n        "description": "Enable strict validation (default: true)"\n      }\n    },\n    "required": ["config"]\n  }\n}\n```\n\n**Example Usage**:\n\n```\n# Validate configuration\nmcp-client provisioning validate_config \\n  --config "$(cat workspaces/prod/database.ncl)"\n\n# With specific schema\nmcp-client provisioning validate_config \\n  --config "workspaces/prod/kubernetes.ncl" \\n  --schema kubernetes\n```\n\n**Response**:\n\n```\n{\n  "valid": true,\n  "errors": [],\n  "warnings": [\n    "Consider enabling automated backups for production use"\n  ],\n  "metadata": {\n    "schema": "kubernetes",\n    "version": "1.28",\n    "validated_at": "2025-01-13T10:45:30Z"\n  }\n}\n```\n\n### 3. Documentation Search\n\n**Tool**: `search_docs`\n\nSearch infrastructure documentation using RAG system.\n\n```\n{\n  "name": "search_docs",\n  "description": "Search provisioning documentation for information",\n  "inputSchema": {\n    "type": "object",\n    "properties": {\n      "query": {\n        "type": "string",\n        "description": "Search query (natural language)"\n      },\n      "top_k": {\n        "type": "integer",\n        "description": "Number of results (default: 5)"\n      },\n      "doc_type": {\n        "type": "string",\n        "enum": ["guide", "schema", "example", "troubleshooting"],\n        "description": "Filter by document type (optional)"\n      }\n    },\n    "required": ["query"]\n  }\n}\n```\n\n**Example Usage**:\n\n```\n# Search documentation\nmcp-client provisioning search_docs \\n  --query "How do I configure PostgreSQL with replication?"\n\n# Get examples\nmcp-client provisioning search_docs \\n  --query "Kubernetes networking" \\n  --doc_type example \\n  --top_k 3\n```\n\n**Response**:\n\n```\n{\n  "results": [\n    {\n      "source": "provisioning/docs/src/guides/database-replication.md",\n      "excerpt": "PostgreSQL logical replication enables streaming of changes...",\n      "relevance": 0.94,\n      "section": "Setup Logical Replication"\n    },\n    {\n      "source": "provisioning/schemas/database.ncl",\n      "excerpt": "replication = { enabled = true, mode = \"logical\", ... }",\n      "relevance": 0.87,\n      "section": "Replication Configuration"\n    }\n  ]\n}\n```\n\n### 4. Deployment Troubleshooting\n\n**Tool**: `troubleshoot_deployment`\n\nAnalyze deployment failures and suggest fixes.\n\n```\n{\n  "name": "troubleshoot_deployment",\n  "description": "Analyze deployment logs and suggest fixes",\n  "inputSchema": {\n    "type": "object",\n    "properties": {\n      "deployment_id": {\n        "type": "string",\n        "description": "Deployment ID (e.g., 'deploy-2025-01-13-001')"\n      },\n      "logs": {\n        "type": "string",\n        "description": "Deployment logs (optional, if deployment_id not provided)"\n      },\n      "error_analysis_depth": {\n        "type": "string",\n        "enum": ["shallow", "deep"],\n        "description": "Analysis depth (default: deep)"\n      }\n    }\n  }\n}\n```\n\n**Example Usage**:\n\n```\n# Troubleshoot recent deployment\nmcp-client provisioning troubleshoot_deployment \\n  --deployment_id "deploy-2025-01-13-001"\n\n# With custom logs\nmcp-client provisioning troubleshoot_deployment \\n| --logs "$(journalctl -u provisioning --no-pager | tail -100)" |\n```\n\n**Response**:\n\n```\n{\n  "status": "failure",\n  "root_cause": "Database connection timeout during migration phase",\n  "analysis": {\n    "phase": "database_migration",\n    "error_type": "connectivity",\n    "confidence": 0.95\n  },\n  "suggestions": [\n    "Verify database security group allows inbound on port 5432",\n    "Check database instance status (may be rebooting)",\n    "Increase connection timeout in configuration"\n  ],\n  "corrected_config": "...generated Nickel config with fixes...",\n  "similar_issues": [\n    "[https://docs/troubleshooting/database-connectivity.md"](https://docs/troubleshooting/database-connectivity.md")\n  ]\n}\n```\n\n### 5. Get Schema\n\n**Tool**: `get_schema`\n\nRetrieve schema definition with examples.\n\n```\n{\n  "name": "get_schema",\n  "description": "Get a provisioning schema definition",\n  "inputSchema": {\n    "type": "object",\n    "properties": {\n      "schema_name": {\n        "type": "string",\n        "description": "Schema name (e.g., 'database', 'kubernetes')"\n      },\n      "format": {\n        "type": "string",\n        "enum": ["schema", "example", "documentation"],\n        "description": "Response format (default: schema)"\n      }\n    },\n    "required": ["schema_name"]\n  }\n}\n```\n\n**Example Usage**:\n\n```\n# Get schema definition\nmcp-client provisioning get_schema --schema_name database\n\n# Get example configuration\nmcp-client provisioning get_schema \\n  --schema_name kubernetes \\n  --format example\n```\n\n### 6. Compliance Check\n\n**Tool**: `check_compliance`\n\nVerify configuration against compliance policies (Cedar).\n\n```\n{\n  "name": "check_compliance",\n  "description": "Check configuration against compliance policies",\n  "inputSchema": {\n    "type": "object",\n    "properties": {\n      "config": {\n        "type": "string",\n        "description": "Configuration to check"\n      },\n      "policy_set": {\n        "type": "string",\n        "description": "Policy set to check against (e.g., 'pci-dss', 'hipaa', 'sox')"\n      }\n    },\n    "required": ["config", "policy_set"]\n  }\n}\n```\n\n**Example Usage**:\n\n```\n# Check against PCI-DSS\nmcp-client provisioning check_compliance \\n  --config "$(cat workspaces/prod/database.ncl)" \\n  --policy_set pci-dss\n```\n\n## Integration Examples\n\n### Claude Desktop (Most Common)\n\n```\n~/.claude/claude_desktop_config.json:\n{\n  "mcpServers": {\n    "provisioning": {\n      "command": "provisioning-mcp-server",\n      "args": ["--config", "/etc/provisioning/ai.toml"],\n      "env": {\n        "PROVISIONING_API_KEY": "sk-...",\n        "PROVISIONING_BASE_URL": "[http://localhost:8083"](http://localhost:8083")\n      }\n    }\n  }\n}\n```\n\n**Usage in Claude**:\n\n```\nUser: I need a production Kubernetes cluster in AWS with automatic scaling\n\nClaude can now use provisioning tools:\nI'll help you create a production Kubernetes cluster. Let me:\n1. Search the documentation for best practices\n2. Generate a configuration template\n3. Validate it against your policies\n4. Provide the final configuration\n```\n\n### OpenAI Function Calling\n\n```\nimport openai\n\ntools = [\n    {\n        "type": "function",\n        "function": {\n            "name": "generate_config",\n            "description": "Generate infrastructure configuration",\n            "parameters": {\n                "type": "object",\n                "properties": {\n                    "description": {\n                        "type": "string",\n                        "description": "Infrastructure description"\n                    }\n                },\n                "required": ["description"]\n            }\n        }\n    }\n]\n\nresponse = openai.ChatCompletion.create(\n    model="gpt-4",\n    messages=[{"role": "user", "content": "Create a PostgreSQL database"}],\n    tools=tools\n)\n```\n\n### Local LLM Integration (Ollama)\n\n```\n# Start Ollama with provisioning MCP\nOLLAMA_MCP_SERVERS=provisioning://localhost:3000 \\n  ollama serve\n\n# Use with llama2 or mistral\ncurl [http://localhost:11434/api/generate](http://localhost:11434/api/generate) \\n  -d '{\n    "model": "mistral",\n    "prompt": "Create a Kubernetes cluster",\n    "tools": [{"type": "mcp", "server": "provisioning"}]\n  }'\n```\n\n## Error Handling\n\nTools return consistent error responses:\n\n```\n{\n  "error": {\n    "code": "VALIDATION_ERROR",\n    "message": "Configuration has 3 validation errors",\n    "details": [\n      {\n        "field": "database.version",\n        "message": "PostgreSQL version 9.6 is deprecated",\n        "severity": "error"\n      },\n      {\n        "field": "backup.retention_days",\n        "message": "Recommended minimum is 30 days for production",\n        "severity": "warning"\n      }\n    ]\n  }\n}\n```\n\n## Performance\n\n|  | Operation | Latency | Notes |  |\n|  | ----------- | --------- | ------- |  |\n|  | generate_config | 2-5s | Depends on LLM and config complexity |  |\n|  | validate_config | 500-1000ms | Parallel schema validation |  |\n|  | search_docs | 300-800ms | RAG hybrid search |  |\n|  | troubleshoot | 3-8s | Depends on log size and analysis depth |  |\n|  | get_schema | 100-300ms | Cached schema retrieval |  |\n|  | check_compliance | 500-2000ms | Policy evaluation |  |\n\n## Configuration\n\nSee [Configuration Guide](configuration.md) for MCP-specific settings:\n\n- MCP server port and binding\n- Tool registry customization\n- Rate limiting for tool calls\n- Access control (Cedar policies)\n\n## Security\n\n### Authentication\n\n- Tools require valid provisioning API token\n- Token scoped to user's workspace\n- All tool calls authenticated and logged\n\n### Authorization\n\n- Cedar policies control which tools user can call\n- Example: `allow(principal, action, resource)` when `role == "admin"`\n- Detailed audit trail of all tool invocations\n\n### Data Protection\n\n- Secrets never passed through MCP\n- Configuration sanitized before analysis\n- PII removed from logs sent to external LLMs\n\n## Monitoring and Debugging\n\n```\n# Monitor MCP server\nprovisioning admin mcp status\n\n# View MCP tool calls\nprovisioning admin logs --filter "mcp_tools" --tail 100\n\n# Debug tool response\nRUST_LOG=provisioning::mcp=debug provisioning-mcp-server\n```\n\n## Related Documentation\n\n- [Architecture](architecture.md) - AI system overview\n- [RAG System](rag-system.md) - Documentation search\n- [Configuration](configuration.md) - MCP setup\n- [API Reference](api-reference.md) - Detailed API endpoints\n- [ADR-015](../architecture/adr/adr-015-ai-integration-architecture.md) - Design decisions\n\n---\n\n**Last Updated**: 2025-01-13\n**Status**: ✅ Production-Ready\n**MCP Version**: 0.6.0+\n**Supported LLMs**: Claude, GPT-4, Llama, Mistral, all MCP-compatible models
