mrapids 0.1.31

Your OpenAPI, but executable
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
# 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

| Step | Tool | Purpose | Output |
|------|------|---------|--------|
| 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

| Field | Type | Description |
|-------|------|-------------|
| `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

| Feature | Description |
|---------|-------------|
| **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

| Field | Type | Description |
|-------|------|-------------|
| `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

| Code | Description |
|------|-------------|
| `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

| Code | Description |
|------|-------------|
| `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

| Level | Methods | Description |
|-------|---------|-------------|
| `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

| MCP Tool | CLI Command |
|----------|-------------|
| `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

| File | Description |
|------|-------------|
| `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+