# MCP Phase 1 - Semantic + Guidance Schema
## Overview
MicroRapid MCP (Model Context Protocol) implementation for AI agent integration. This document describes the Phase 1 implementation with Semantic + Guidance pattern and Preview Token Enforcement.
## Configuration
### Claude Desktop Config
Location: `~/Library/Application Support/Claude/claude_desktop_config.json`
```json
{
"mcpServers": {
"petstore": {
"command": "/Users/.../.cargo/bin/mrapids",
"args": [
"mcp",
"serve",
"--spec",
"/path/to/specs/api.yaml"
],
"cwd": "/path/to/project"
}
}
}
```
### Configuration Flow
```
Claude Desktop Config
│
▼
"args": ["mcp", "serve", "--spec", "/full/path/to/api.yaml"]
│
▼
McpServer::new(debug, policy, spec) ← spec path passed here
│
▼
self.spec_path = Some("/full/path/to/api.yaml") ← stored in server
│
▼
find_spec_file() checks self.spec_path first ← returns configured path
│
▼
All tools use find_spec_file() to locate the spec
```
---
## MCP Server Architecture
```
┌─────────────────────────────────────────────────────────────────────────────┐
│ MCP SERVER (mrapids) │
├─────────────────────────────────────────────────────────────────────────────┤
│ McpServer { │
│ spec_path: PathBuf ← from --spec config │
│ signing_key: [u8; 32] ← HMAC key for token signing │
│ environment: String ← from MRAPIDS_ENV (default: development)│
│ preview_tokens: HashMap ← active preview tokens │
│ index_store: IndexStore ← operation search index │
│ audit_log_path: PathBuf ← .mrapids/mcp_audit.log │
│ } │
└─────────────────────────────────────────────────────────────────────────────┘
```
---
## Workflow
```
┌──────────┐ ┌──────────┐ ┌───────────┐ ┌─────────────┐ ┌─────────┐
│ api_find │───▶│ api_show │───▶│ api_query │───▶│ api_preview │───▶│ api_run │
└──────────┘ └──────────┘ └───────────┘ └─────────────┘ └─────────┘
│ │ │ │ │
▼ ▼ ▼ ▼ ▼
[operation_id] [overview] [exact params] [preview_id] [response]
[copy-run cmd] [HMAC signed]
```
### Workflow Description
| 1 | `api_find` | Search operations by keyword | List of matching operations |
| 2 | `api_show` | Get operation overview | Method, path, parameters, auth |
| 3 | `api_query` | Get exact parameter details | Copy-run command, body schema |
| 4 | `api_preview` | Preview request, get token | HMAC-signed preview_id |
| 5 | `api_run` | Execute with token | API response |
---
## Tool Schemas
### 1. api_help
List available commands and their CLI equivalents.
**Input Schema:**
```json
{
"type": "object",
"properties": {
"command": {
"type": "string",
"description": "Specific command to get help for (optional)",
"enum": ["find", "show", "query", "preview", "run", "auth"]
}
},
"required": []
}
```
**Example:**
```json
// Input
{}
// Output
{
"data": {
"commands": [
{"name": "api_find", "cli": "mrapids list --search"},
{"name": "api_show", "cli": "mrapids show <operation>"},
{"name": "api_query", "cli": "mrapids run -Q <operation>"},
{"name": "api_preview", "cli": "mrapids run --dry-run"},
{"name": "api_run", "cli": "mrapids run <operation>"},
{"name": "api_auth", "cli": "mrapids auth status"}
]
}
}
```
---
### 2. api_find
Search for API operations by keyword.
**Input Schema:**
```json
{
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "Search query (e.g., 'create pet', 'list users')"
},
"method": {
"type": "string",
"description": "Filter by HTTP method",
"enum": ["GET", "POST", "PUT", "DELETE", "PATCH"]
},
"limit": {
"type": "integer",
"description": "Maximum results (default: 10)",
"default": 10
}
},
"required": ["query"]
}
```
**Example:**
```json
// Input
{"query": "pet", "method": "POST"}
// Output
{
"data": {
"query": "pet",
"results": [
{
"operation_id": "addPet",
"method": "POST",
"path": "/pet",
"summary": "Add a new pet to the store",
"risk_level": "write",
"auth_required": false
}
],
"total_count": 1
},
"guidance": {
"ready": true,
"blockers": [],
"next_action": {
"tool": "api_show",
"params": {"operation_id": "addPet"},
"reason_code": "get_operation_details"
},
"display_hint": "Found 1 result. Call api_show to see details."
}
}
```
---
### 3. api_show
Get operation overview including method, path, parameters, and auth requirements.
**Input Schema:**
```json
{
"type": "object",
"properties": {
"operation_id": {
"type": "string",
"description": "The operation ID (from api_find results)"
}
},
"required": ["operation_id"]
}
```
**Example:**
```json
// Input
{"operation_id": "addPet"}
// Output
{
"data": {
"operation_id": "addPet",
"method": "POST",
"path": "/pet",
"summary": "Add a new pet to the store",
"url": "https://petstore.swagger.io/v2/pet",
"parameters": [
{"name": "body", "in": "body", "type": "object", "required": true}
],
"risk": {
"level": "write",
"side_effects": ["creates_resource"],
"idempotent": false,
"requires_confirmation": false
},
"auth": {
"required": false,
"configured": true
}
},
"guidance": {
"ready": true,
"blockers": [],
"next_action": {
"tool": "api_query",
"params": {"operation_id": "addPet"},
"reason_code": "get_parameter_details"
},
"display_hint": "Call api_query to get exact parameter details"
}
}
```
---
### 4. api_query
Get exact parameter details and ready-to-use command. Equivalent to `mrapids run -Q`.
**Input Schema:**
```json
{
"type": "object",
"properties": {
"operation_id": {
"type": "string",
"description": "The operation ID"
}
},
"required": ["operation_id"]
}
```
**Example:**
```json
// Input
{"operation_id": "addPet"}
// Output
{
"data": {
"operation_id": "addPet",
"method": "POST",
"path": "/pet",
"url": "https://petstore.swagger.io/v2/pet",
"path_parameters": [],
"query_parameters": [],
"header_parameters": [],
"body_schema": {
"type": "object",
"required": ["name", "photoUrls"],
"properties": {
"name": {"type": "string"},
"photoUrls": {"type": "array", "items": {"type": "string"}},
"status": {"type": "string", "enum": ["available", "pending", "sold"]}
}
},
"copy_run_command": "mrapids run addPet \\\n --data '{\"name\": \"...\", \"photoUrls\": []}'",
"tips": ["--dry-run to preview", "-v for verbose", "--as-curl for curl command"]
},
"guidance": {
"ready": true,
"blockers": [],
"next_action": {
"tool": "api_preview",
"params": {"operation_id": "addPet", "body": {}},
"reason_code": "preview_before_execute"
},
"display_hint": "Call api_preview with body to get execution token"
}
}
```
---
### 5. api_preview
Preview the request and get an execution token. **REQUIRED before api_run.**
**Input Schema:**
```json
{
"type": "object",
"properties": {
"operation_id": {
"type": "string",
"description": "The operation ID"
},
"params": {
"type": "object",
"description": "Path and query parameters as key-value pairs",
"additionalProperties": true
},
"body": {
"type": "object",
"description": "Request body for POST/PUT/PATCH",
"additionalProperties": true
}
},
"required": ["operation_id"]
}
```
**Example:**
```json
// Input
{
"operation_id": "addPet",
"body": {
"name": "doggy",
"photoUrls": [],
"status": "available"
}
}
// Output
{
"data": {
"preview_id": "eyJpZCI6InByZXZfYWJjMTIzIiwib3Blc...",
"expires_in_seconds": 300,
"request": {
"method": "POST",
"url": "https://petstore.swagger.io/v2/pet",
"headers": {
"Content-Type": "application/json",
"Authorization": "[REDACTED]"
},
"body": {"name": "doggy", "photoUrls": [], "status": "available"}
},
"risk": {
"level": "write",
"side_effects": ["creates_resource"],
"idempotent": false,
"requires_confirmation": false
}
},
"guidance": {
"ready": true,
"blockers": [],
"next_action": {
"tool": "api_run",
"params": {"preview_id": "prev_abc123"},
"reason_code": "execute_previewed_request"
},
"display_hint": "Request looks correct. Call api_run with preview_id to execute."
}
}
```
---
### 6. api_run
Execute an API operation. **REQUIRES a valid preview_id from api_preview.**
**Input Schema:**
```json
{
"type": "object",
"properties": {
"preview_id": {
"type": "string",
"description": "The preview token from api_preview (REQUIRED)"
}
},
"required": ["preview_id"]
}
```
**Example:**
```json
// Input
{"preview_id": "eyJpZCI6InByZXZfYWJjMTIzIiwib3Blc..."}
// Output (Success)
{
"data": {
"success": true,
"status_code": 200,
"response": {
"id": 12345,
"name": "doggy",
"photoUrls": [],
"status": "available"
}
},
"guidance": {
"ready": true,
"blockers": [],
"next_action": {"tool": null, "reason_code": "complete"},
"display_hint": "Operation executed successfully."
}
}
// Output (Error - No token)
{
"data": {"error": "Missing preview_id"},
"guidance": {
"ready": false,
"blockers": [{
"code": "missing_preview_token",
"message": "Call api_preview first to get a token"
}]
}
}
// Output (Error - Expired token)
{
"data": {"error": "Token expired"},
"guidance": {
"ready": false,
"blockers": [{
"code": "token_expired",
"message": "Preview token has expired. Generate a new one.",
"resolution": {
"tool": "api_preview",
"params": {"operation_id": "addPet"}
}
}]
}
}
```
---
### 7. api_auth
Check authentication status.
**Input Schema:**
```json
{
"type": "object",
"properties": {},
"required": []
}
```
**Example:**
```json
// Input
{}
// Output
{
"data": {
"configured": true,
"methods": [
{"type": "api_key", "name": "api_key", "configured": true},
{"type": "oauth2", "name": "petstore_auth", "configured": false}
]
},
"guidance": {
"ready": true,
"display_hint": "API key authentication is configured."
}
}
```
---
## Preview Token Structure
The preview token is a HMAC-signed, base64-encoded JSON payload:
```
preview_id = base64(JSON) + "." + HMAC-SHA256(JSON, signing_key)
```
### Token Payload
```json
{
"id": "prev_abc123def456",
"operation_id": "addPet",
"request_hash": "f043f3d6d8609b121086daef11d4fa34174ec09e55dae348d75ad9889e4d08f8",
"environment": "development",
"base_url": "https://petstore.swagger.io/v2",
"risk_level": "write",
"requires_confirmation": false,
"confirmed": false,
"created_at": 1766893505,
"expires_at": 1766893805,
"params": {},
"body": {"name": "doggy", "photoUrls": [], "status": "available"}
}
```
### Token Fields
| `id` | string | Unique token identifier (prev_xxxx) |
| `operation_id` | string | The API operation to execute |
| `request_hash` | string | SHA256 hash of the full request |
| `environment` | string | Execution environment |
| `base_url` | string | API base URL |
| `risk_level` | enum | read, write, destructive |
| `requires_confirmation` | bool | True for destructive operations |
| `confirmed` | bool | User confirmation status |
| `created_at` | i64 | Unix timestamp of creation |
| `expires_at` | i64 | Unix timestamp of expiry (5 min) |
| `params` | object | Path/query parameters |
| `body` | object | Request body (if any) |
---
## Security Flow
```
┌────────────┐ ┌─────────────┐ ┌───────────┐ ┌──────────┐
│ Claude │────▶│ api_preview │────▶│ Verify │────▶│ api_run │
│ Agent │ │ │ │ + Sign │ │ │
└────────────┘ └─────────────┘ └───────────┘ └──────────┘
│ │ │
▼ ▼ ▼
┌─────────────┐ ┌───────────┐ ┌───────────┐
│ Build │ │ HMAC-256 │ │ Verify │
│ Request │ │ Sign │ │ Signature │
│ Preview │ │ Token │ │ + Expiry │
└─────────────┘ └───────────┘ └───────────┘
│
┌───────────────┴───────────────┐
▼ ▼
┌─────────────┐ ┌─────────────┐
│ Valid │ │ Invalid │
│ Execute │ │ Reject │
└─────────────┘ └─────────────┘
```
### Security Features
| **Zero Trust** | Every request validated against policies |
| **Credential Isolation** | AI never sees raw tokens/passwords |
| **Preview Enforcement** | No execution without valid preview_id |
| **HMAC Signing** | Tokens are tamper-proof |
| **Token Expiry** | 5-minute validity window |
| **Audit Logging** | Complete log of all AI actions |
---
## Guidance Pattern
Every response includes a `guidance` block:
```json
{
"guidance": {
"ready": true,
"blockers": [],
"next_action": {
"tool": "api_show",
"params": {"operation_id": "addPet"},
"reason_code": "get_operation_details"
},
"display_hint": "Call api_show to see operation details",
"alternatives": []
}
}
```
### Guidance Fields
| `ready` | bool | Can proceed to next step |
| `blockers` | array | Issues preventing progress |
| `next_action` | object | Recommended next tool call |
| `display_hint` | string | Human-readable suggestion |
| `alternatives` | array | Other possible actions |
### Blocker Codes
| `missing_parameter` | Required parameter not provided |
| `invalid_input` | Parameter value is invalid |
| `auth_required` | Authentication needed |
| `auth_not_configured` | Credentials not set up |
| `operation_not_found` | Operation doesn't exist |
| `missing_preview_token` | api_run called without token |
| `token_expired` | Preview token has expired |
| `token_invalid` | Token signature verification failed |
| `environment_mismatch` | Token env differs from current |
### Reason Codes
| `get_operation_details` | Need more info about operation |
| `get_parameter_details` | Need exact parameter specs |
| `preview_before_execute` | Must preview before running |
| `execute_previewed_request` | Ready to execute |
| `retry_with_correction` | Fix issue and retry |
| `confirm_destructive_action` | User must confirm DELETE |
| `complete` | Workflow finished |
---
## Risk Levels
| `read` | GET, HEAD, OPTIONS | No side effects |
| `write` | POST, PUT, PATCH | Creates/modifies data |
| `destructive` | DELETE | Irreversible changes |
### Risk Profile
```json
{
"level": "write",
"side_effects": ["creates_resource"],
"idempotent": false,
"requires_confirmation": false
}
```
---
## CLI Equivalents
| `api_help` | `mrapids --help` |
| `api_find` | `mrapids list --search <query>` |
| `api_show` | `mrapids show <operation>` |
| `api_query` | `mrapids run -Q <operation>` |
| `api_preview` | `mrapids run <operation> --dry-run` |
| `api_run` | `mrapids run <operation>` |
| `api_auth` | `mrapids auth status` |
---
## Testing
### Test MCP Tools
```bash
# From project directory with specs/api.yaml
cd /path/to/petstore
# Test api_find
mrapids mcp test api_find --query "pet"
# Test api_show
mrapids mcp test api_show --operation "addPet"
# Test api_query
mrapids mcp test api_query --operation "addPet"
# Test api_preview
mrapids mcp test api_preview --operation "addPet" --params '{"body": {"name": "test"}}'
# Test api_run (use preview_id from api_preview output)
mrapids mcp test api_run --operation "<preview_id>"
```
### Check MCP Status
```bash
mrapids mcp status
```
### Start MCP Server (for debugging)
```bash
mrapids mcp serve --spec /path/to/api.yaml --debug
```
---
## Files
| `src/core/mcp.rs` | MCP server implementation |
| `src/core/mcp_types.rs` | Type definitions |
| `.mrapids/index.db` | Operation search index |
| `.mrapids/mcp_audit.log` | Audit log |
| `~/.mrapids/mcp_key` | HMAC signing key |
---
## Version
- **Phase**: 1
- **Pattern**: Semantic + Guidance
- **Security**: Preview Token Enforcement
- **MicroRapid Version**: 0.1.30+