# Spec Slice — OpenAPI & GraphQL Subgraph Extractor (v1.0.0)

> Shrink 200k-token OpenAPI 3.1 and GraphQL schemas by 90-99% into valid, cycle-safe mini-specs in <20ms.

Surgical OpenAPI 3.0/3.1, Swagger 2.0, and GraphQL SDL subgraph slicer for coding and tool-use agents. Ranks operations by BM25 intent + structural boosts and extracts the exact cycle-safe transitive closure of referenced schemas, parameters, unions, interfaces, inputs, and enums.

## Why Agents Use This API Instead of DIY
Eliminates context-window overflow on massive Stripe/GitHub/Shopify specs, avoids broken $ref pointers or infinite recursive schema loops, and saves $0.10-$0.50 in LLM input tokens for $0.001.

## Connection & Payment (x402 Default + Optional Bearer API Key)
- **MCP Server (Streamable HTTP):** `https://spec-slice.apikeg.com/mcp` (Registry ID: `com.apikeg/spec-slice` — `initialize`, `tools/list`, `resources/*`, and `prompts/*` are free)
- **OpenAPI 3.1 Spec:** [openapi.json](https://spec-slice.apikeg.com/openapi.json)
- **Full Schema & Examples:** [llms-full.txt](https://spec-slice.apikeg.com/llms-full.txt)
- **RFC 9727 API Catalog:** [.well-known/api-catalog](https://spec-slice.apikeg.com/.well-known/api-catalog)
- **x402 Bazaar Manifest:** [.well-known/x402.json](https://spec-slice.apikeg.com/.well-known/x402.json)
- **MCP Discovery Manifest:** [.well-known/mcp.json](https://spec-slice.apikeg.com/.well-known/mcp.json)
- **A2A Agent Card:** [.well-known/agent-card.json](https://spec-slice.apikeg.com/.well-known/agent-card.json)
- **Primary Payment (Zero Signup):** Cloudflare Monetization Gateway (`HTTP 402` / `x402` v2 with USDC on Base).
- **Optional Monthly API Key:** Pass `Authorization: Bearer ak_live_...` ($5 / $20 / $50 monthly per-product Stripe plans at [apikeg.com/account](https://apikeg.com/account)).
- **Free Preflight:** Append `?dry_run=true` (or header `X-Dry-Run: true`) to validate any request payload at `$0.00` cost.

## Tools & REST Endpoints
- [`slice_openapi_spec`](https://spec-slice.apikeg.com/tools/slice-openapi-spec.md) (`POST https://spec-slice.apikeg.com/v1/slice-openapi-spec`) — $0.001 USD per OpenAPI/Swagger subgraph slice (x402 instant micropayment): Scores OpenAPI/Swagger endpoints against a natural-language `query` (BM25 + boosted `operationId`, `summary`, `tags`, and path tokens) or explicit `operationIds`/`pathPatterns`, walks every reachable JSON Pointer `$ref` with cycle protection, prunes unused paths/components, and emits ready-to-use `curl` + TypeScript `fetch` snippets.
- [`slice_graphql_schema`](https://spec-slice.apikeg.com/tools/slice-graphql-schema.md) (`POST https://spec-slice.apikeg.com/v1/slice-graphql-schema`) — $0.001 USD per GraphQL SDL subgraph slice (x402 instant micropayment): Parses GraphQL Schema Definition Language (`Query`, `Mutation`, `Subscription`, `type`, `input`, `interface`, `union`, `enum`, `scalar`), scores root fields against `query` or explicit `rootFields`, and emits a valid mini-SDL containing only selected root fields and the transitive closure of referenced types.

## Instant MCP Configuration
```json
{
  "mcpServers": {
    "spec-slice": {
      "type": "streamable-http",
      "url": "https://spec-slice.apikeg.com/mcp"
    }
  }
}
```

## Common Agent Use Cases
- slice large OpenAPI spec for LLM context window
- extract OpenAPI 3.1 endpoints and transitive $ref schemas
- prune GraphQL SDL schema to relevant Query and Mutation subgraph
- compress Swagger 2.0 JSON for AI coding agent
- generate curl and TypeScript fetch from OpenAPI operation

---

## Detailed Tool Specifications

### `slice_openapi_spec` — Slice OpenAPI 3.0/3.1 or Swagger 2.0 Specification
- **REST Endpoint:** `POST https://spec-slice.apikeg.com/v1/slice-openapi-spec`
- **Tool Doc Page:** https://spec-slice.apikeg.com/tools/slice-openapi-spec
- **MCP Tool Name:** `slice_openapi_spec`
- **Pricing:** $0.001 USD per OpenAPI/Swagger subgraph slice (x402 instant micropayment)
- **Side Effects:** readOnly=true, idempotent=true, destructive=false
- **Build vs. Buy ROI:** Saves 50,000-250,000 prompt tokens per large enterprise OpenAPI spec ($0.15+ LLM input cost) while guaranteeing zero broken `#/components/...` `$ref` links or recursive schema crashes.

#### Input JSON Schema
```json
{
  "type": "object",
  "properties": {
    "spec": {
      "description": "OpenAPI 3.0/3.1 or Swagger 2.0 specification provided as either a parsed JSON object or a serialized JSON string (up to 5 MiB)."
    },
    "query": {
      "type": "string",
      "maxLength": 500,
      "description": "Natural-language task intent (e.g. 'create credit note and refund invoice') scored via Okapi BM25 plus boosted matches on operationId, summary, tags, and path segments."
    },
    "operationIds": {
      "type": "array",
      "items": {
        "type": "string",
        "minLength": 1,
        "maxLength": 200
      },
      "maxItems": 50,
      "description": "Explicit operationId values to extract (case-insensitive)."
    },
    "pathPatterns": {
      "type": "array",
      "items": {
        "type": "string",
        "minLength": 1,
        "maxLength": 300
      },
      "maxItems": 50,
      "description": "Explicit path templates or 'METHOD /v1/path/*' glob patterns to extract (e.g. 'POST /v1/invoices/*/refund')."
    },
    "methods": {
      "type": "array",
      "items": {
        "type": "string",
        "enum": [
          "GET",
          "POST",
          "PUT",
          "PATCH",
          "DELETE",
          "HEAD",
          "OPTIONS",
          "TRACE"
        ]
      },
      "maxItems": 8,
      "description": "Optional HTTP method allowlist."
    },
    "maxOperations": {
      "type": "integer",
      "default": 5,
      "minimum": 1,
      "maximum": 50,
      "description": "Maximum number of matched operations to retain in the sliced OpenAPI spec."
    },
    "compactDescriptions": {
      "type": "boolean",
      "default": false,
      "description": "Strip verbose prose descriptions, examples, and externalDocs while keeping spec-valid response descriptions."
    },
    "includeSnippets": {
      "type": "boolean",
      "default": true,
      "description": "Generate ready-to-use curl and TypeScript fetch code snippets for each selected operation."
    }
  },
  "required": [
    "spec"
  ],
  "additionalProperties": false
}
```

#### Examples
**Extract refund & credit-note endpoints from billing OpenAPI spec** — Finds matching operations via BM25 and retains only reachable component schemas.
```bash
curl -X POST "https://spec-slice.apikeg.com/v1/slice-openapi-spec" \
  -H "Content-Type: application/json" \
  -d '{"query":"create credit note and refund invoice","maxOperations":2,"compactDescriptions":true,"includeSnippets":true,"spec":{"openapi":"3.1.0","info":{"title":"Billing API","version":"2.4.0"},"servers":[{"url":"https://api.billing.example.com"}],"paths":{"/v1/invoices/{invoiceId}/refunds":{"post":{"operationId":"refundInvoice","summary":"Refund an invoice","tags":["Invoices"],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/RefundRequest"}}}},"responses":{"200":{"description":"Refund created","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Refund"}}}}}}},"/v1/warehouses":{"get":{"operationId":"listWarehouses","summary":"List inventory warehouses","responses":{"200":{"description":"OK","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Warehouse"}}}}}}}},"components":{"schemas":{"RefundRequest":{"type":"object","required":["amountCents"],"properties":{"amountCents":{"type":"integer"}}},"Refund":{"type":"object","properties":{"id":{"type":"string"},"status":{"type":"string"}}},"Warehouse":{"type":"object","properties":{"id":{"type":"string"},"location":{"type":"string"}}}}}}}'
```
Expected result: Retains refundInvoice + RefundRequest + Refund, prunes listWarehouses + Warehouse, and emits curl + TypeScript fetch snippets.

### `slice_graphql_schema` — Slice GraphQL SDL Schema to Minimal Subgraph
- **REST Endpoint:** `POST https://spec-slice.apikeg.com/v1/slice-graphql-schema`
- **Tool Doc Page:** https://spec-slice.apikeg.com/tools/slice-graphql-schema
- **MCP Tool Name:** `slice_graphql_schema`
- **Pricing:** $0.001 USD per GraphQL SDL subgraph slice (x402 instant micropayment)
- **Side Effects:** readOnly=true, idempotent=true, destructive=false
- **Build vs. Buy ROI:** Replaces heavyweight `graphql-js` AST bundlers on edge runtimes and shrinks 10,000-line federated GraphQL schemas into minimal, copy-pasteable mini-SDL + sample operations.

#### Input JSON Schema
```json
{
  "type": "object",
  "properties": {
    "sdl": {
      "type": "string",
      "minLength": 1,
      "description": "Full GraphQL Schema Definition Language (SDL) string."
    },
    "query": {
      "type": "string",
      "maxLength": 500,
      "description": "Natural-language task intent scored against root Query, Mutation, and Subscription fields."
    },
    "rootFields": {
      "type": "array",
      "items": {
        "type": "string",
        "minLength": 1,
        "maxLength": 200
      },
      "maxItems": 50,
      "description": "Explicit root field names to extract (e.g. 'createCreditNote' or 'Mutation.refundInvoice')."
    },
    "operationTypes": {
      "type": "array",
      "items": {
        "type": "string",
        "enum": [
          "Query",
          "Mutation",
          "Subscription"
        ]
      },
      "maxItems": 3,
      "description": "Optional filter restricting root operation containers."
    },
    "maxRootFields": {
      "type": "integer",
      "default": 5,
      "minimum": 1,
      "maximum": 50,
      "description": "Maximum number of matched root fields to retain in the mini-SDL."
    },
    "compactDescriptions": {
      "type": "boolean",
      "default": false,
      "description": "Strip triple-quoted and single-line descriptions from the emitted mini-SDL."
    }
  },
  "required": [
    "sdl"
  ],
  "additionalProperties": false
}
```

#### Examples
**Slice GraphQL Mutation for issuing a credit note**
```bash
curl -X POST "https://spec-slice.apikeg.com/v1/slice-graphql-schema" \
  -H "Content-Type: application/json" \
  -d '{"query":"issue credit note for invoice","maxRootFields":2,"compactDescriptions":true,"sdl":"scalar DateTime\nenum CreditReason { DUPLICATE OVERCHARGE }\ninput IssueCreditNoteInput { invoiceId: ID! reason: CreditReason! }\ntype CreditNote { id: ID! issuedAt: DateTime! }\ntype Warehouse { id: ID! code: String! }\ntype Query { warehouses: [Warehouse!]! }\ntype Mutation { issueCreditNote(input: IssueCreditNoteInput!): CreditNote! }"}'
```
Expected result: Emits mini-SDL with DateTime, CreditReason, IssueCreditNoteInput, CreditNote, and Mutation.issueCreditNote while pruning Warehouse and Query.warehouses.
