> ## Documentation Index
> Fetch the complete documentation index at: https://docs.ctxprotocol.com/llms.txt
> Use this file to discover all available pages before exploring further.

# MCP Server

> Connect any MCP-compatible agent to the Context marketplace

## Overview

Context provides a remote MCP server that exposes the entire marketplace (Query, Execute, and Discover) through the [Model Context Protocol](https://modelcontextprotocol.io). Any agent that supports Streamable HTTP MCP servers can connect in under a minute.

**Five tools are available:**

| Tool                   | What it does                                                                                                       |
| ---------------------- | ------------------------------------------------------------------------------------------------------------------ |
| `context_query`        | Run an agentic Q\&A query against the marketplace. Quick jobs return a grounded answer; long jobs return a `jobId` |
| `context_query_start`  | Start a complex query and return a `jobId` immediately                                                             |
| `context_query_status` | Poll a query job until it completes or fails                                                                       |
| `context_execute`      | Call a specific marketplace tool method directly and get the structured result                                     |
| `context_discover`     | Search the marketplace for available tools before querying or executing                                            |

<Note>
  The MCP server wraps the same Query and Execute APIs that the TypeScript and Python SDKs use. Authentication is the same `sk_live_...` API key you already have.
</Note>

<Tip>
  Building a daily report, alert, or repeatable data pipeline? See [Agent Data Routines](/sdk/agent-routines) for the progression from natural-language Query to `evidence_only`, `dataUrl`, pinned tools, and optional direct execution.
</Tip>

***

## Prerequisites

Before connecting, complete setup at [ctxprotocol.com](https://ctxprotocol.com):

<Steps>
  <Step title="Sign in">
    Creates your embedded wallet
  </Step>

  <Step title="Set spending cap">
    Approve USDC spending on the ContextRouter (one-time)
  </Step>

  <Step title="Fund wallet">
    Add USDC for tool execution fees
  </Step>

  <Step title="Generate API key">
    Settings → API Keys → Create key starting with `sk_live_`
  </Step>
</Steps>

***

## Endpoint

```
https://www.ctxprotocol.com/api/mcp
```

Transport: **Streamable HTTP** (the standard for remote MCP servers).

Authentication: `Authorization: Bearer sk_live_...` header on every request.

***

## Setup by Agent

### Cursor

Add to your project's `.cursor/mcp.json` (or your global MCP settings):

```json theme={null}
{
  "mcpServers": {
    "ctxprotocol": {
      "url": "https://www.ctxprotocol.com/api/mcp",
      "headers": {
        "Authorization": "Bearer sk_live_YOUR_KEY"
      }
    }
  }
}
```

Restart Cursor. The five tools appear in your MCP tool list automatically. If `context_query_status` is missing after a deploy, refresh or restart the MCP server before testing long jobs.

### Claude Code

```bash theme={null}
claude mcp add --transport http ctxprotocol https://www.ctxprotocol.com/api/mcp \
  --header "Authorization: Bearer sk_live_YOUR_KEY"
```

### OpenClaw / Claw Code

Add to your project's `mcp.json` or pass via CLI:

```json theme={null}
{
  "mcpServers": {
    "ctxprotocol": {
      "transport": "streamable-http",
      "url": "https://www.ctxprotocol.com/api/mcp",
      "headers": {
        "Authorization": "Bearer sk_live_YOUR_KEY"
      }
    }
  }
}
```

### Any MCP Client (Generic)

Any client that supports Streamable HTTP transport can connect by pointing to:

* **URL**: `https://www.ctxprotocol.com/api/mcp`
* **Transport**: Streamable HTTP
* **Auth header**: `Authorization: Bearer sk_live_YOUR_KEY`

The server returns a `Mcp-Session-Id` header after initialization. Clients that support session persistence should send it back on subsequent requests.

***

## Tools Reference

### context\_query

Ask a natural-language question and get a grounded answer powered by the full marketplace.

| Parameter               | Type      | Required | Description                                                                                                                                       |
| ----------------------- | --------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
| `question`              | string    | Yes      | The question to answer (1–4000 chars)                                                                                                             |
| `agentModelId`          | string    | No       | Advanced: choose the main librarian agent model for the merged execution/final-response loop                                                      |
| `responseShape`         | string    | No       | `answer_with_evidence` (default) or `evidence_only`. See [Answer vs evidence](#answer-vs-evidence)                                                |
| `toolIds`               | string\[] | No       | Restrict query to specific tool UUIDs (Manual Mode). Omit for Auto Mode discovery and selection                                                   |
| `favoritesOnly`         | boolean   | No       | Override the account-level Favorites-Only Auto Mode for this request                                                                              |
| `includeData`           | boolean   | No       | Include bounded execution data inline. Large payloads return a preview plus full-data references                                                  |
| `includeDataUrl`        | boolean   | No       | Persist the full execution data and return a URL, keeping large payloads out of your context window. Defaults to true in the ctxprotocol MCP tool |
| `includeDeveloperTrace` | boolean   | No       | Include a machine-readable runtime trace (tool selection, retries, loops) for debugging                                                           |

<Note>
  The runtime auto-selects execution depth and the internal tool-selection model per request. `agentModelId` is optional and controls the main librarian loop only; most callers can omit it. MCP clients can inspect the `agentModelId` schema enum to see valid slugs. When omitted, the managed default is `kimi-k2.6-model` (same as `DEFAULT_AGENT_MODEL_ID` in the SDK).
</Note>

**Example prompt to your agent:**

> Use the context\_query tool to answer: "What are the top Polymarket markets by volume right now?"

The response includes the answer text, structured evidence, and metadata.

For long jobs, `context_query` may return a `jobId` before the answer is ready. Poll `context_query_status` with that exact `jobId`; do not call `context_query` again for the same question unless you want to start a duplicate paid query.

<Info>
  If the API key owner enables Favorites-Only Auto Mode in [Settings](https://ctxprotocol.com/settings), `context_query` and `context_discover` inherit that account default automatically. Pass `favoritesOnly: true` or `favoritesOnly: false` on a single MCP call to override it. If you pass explicit `toolIds` to `context_query`, manual tool selection wins and favorites filtering is ignored.
</Info>

### Auto Mode vs Manual Mode

`context_query` is the default one-call product surface:

* **Auto Mode:** omit `toolIds`. The runtime runs marketplace discovery, selects tools with its managed selector, executes the librarian loop, and returns grounded output.
* **Named-provider Auto Mode:** if a normal natural-language question names providers or venues, keep those names in the `question` text and still omit `toolIds`. For example, "using Crypto Positioning and Crypto Data" should usually stay Auto Mode unless the user explicitly asks to pin tools.
* **Manual Mode:** pass `toolIds` from `context_discover` only when you explicitly want to pin/inspect tools or bypass broad marketplace selection. The runtime skips broad marketplace selection and runs the same librarian loop using only those tools.
* **Agent-driven mode:** use `context_discover` + `context_execute` only when your host agent wants to drive exact method calls and synthesis itself.

<Tip>
  For natural-language questions, start with `context_query` and answer from that result. It already performed managed discovery, selection, execution, grounding, and chart/artifact generation. Avoid `context_discover`, artifact fetching, or a follow-up `context_execute` verification pass unless you need raw method output, exact rows, or explicitly pinned tools.
</Tip>

### Async Query Jobs

Some marketplace questions are slow: multi-tool analysis, chart generation, long historical windows, large data exports, and code-interpreter post-processing can exceed an MCP host's direct tool-call window. Context handles this with durable query jobs: the backend librarian runtime keeps running discovery, tool calls, Python/code-interpreter work, chart generation, grounding, and synthesis after the initial MCP call returns a `jobId`.

This is the same managed Query runtime, not a lightweight background fetch. The `jobId` is just the handle your MCP client uses while Context continues the long-running work server-side.

| Tool                   | When to use                                               | Next step                                                                           |
| ---------------------- | --------------------------------------------------------- | ----------------------------------------------------------------------------------- |
| `context_query`        | Default natural-language workflow                         | If it returns an answer, use it. If it returns `jobId`, call `context_query_status` |
| `context_query_start`  | You know the job is complex and want a handle immediately | Call `context_query_status`                                                         |
| `context_query_status` | You have a `jobId`                                        | Poll until `completed` or `failed`                                                  |

<Warning>
  Do not start another `context_query` for the same prompt after receiving a `jobId`. That creates a second paid query. Poll `context_query_status` instead.
</Warning>

<Tip>
  For Cursor specifically, keep the loop simple: one `context_query` or `context_query_start`, then `context_query_status`. While status is `running`, do not inspect local files, fetch blobs, or start a duplicate query. If the status tool is not visible in Cursor's MCP tool list, refresh/restart the MCP server rather than falling back to file searches or shell polling.
</Tip>

### Answer vs evidence

`responseShape` controls whether Context adds a prose synthesis layer on top of the grounded result. Both shapes run the same managed runtime (discover, select, execute, ground); they differ only in what comes back.

| Shape                            | Returns                                                                                                     | Use when                                                                                                    |
| -------------------------------- | ----------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- |
| `answer_with_evidence` (default) | A written answer plus structured `evidence`, `summary`, `artifacts`, `freshness`, `confidence`, and `usage` | You want a ready-to-read answer, or chat-parity output                                                      |
| `evidence_only`                  | Bounded `evidence`, optional bounded `data`, `computedArtifacts`, and full-data references with no prose    | Your own agent (Cursor, Claude Code) is the synthesizer and wants grounded facts plus artifact/data handles |

For `evidence_only`, unbounded raw data is not returned inline by default. Use the default evidence envelope and `computedArtifacts` inline, then fetch the full dataset from `dataUrl`/`artifacts.canonicalDataRef` when needed. If you set `includeData: true`, large payloads are still capped and returned as a truncation preview.

<Note>
  The full machine-readable payload is always in the MCP `structuredContent` field. The text content mirrors it, so hosts that only forward text still receive the evidence. If the response includes chart artifacts, the text content also includes markdown image links so agents can surface the charts to users.
</Note>

<Tip>
  For recurring agent-written reports, use `responseShape: "evidence_only"` with `includeDataUrl: true`. Let the host agent read the bounded evidence first, then fetch `dataUrl` only when it needs full rows for local computation.
</Tip>

<Tip>
  For routine recipe capture, read `toolsUsed` from the terminal structured result before fetching raw data. Direct `context_query` returns it at `structuredContent.toolsUsed`; completed `context_query_status` returns it at `structuredContent.result.toolsUsed`. Text-only hosts should show "Routine recipe tool candidates from toolsUsed".
</Tip>

<Warning>
  Large `dataUrl` files should be fetched with the SDK, Node/Python `fetch`, `curl`, or another real HTTP client. Browser-style webpage fetchers and summarizers may truncate multi-MB JSON.
</Warning>

### Ambiguity And Capability Misses

When a request is ambiguous, the runtime answers with its best grounded assumption rather than blocking and may include `assumptionMade` in `structuredContent`. If no marketplace tool can satisfy the request, the response uses `outcomeType: "capability_miss"` with a typed `capabilityMiss` payload and suggested rewrites.

### context\_execute

Call a specific tool method with explicit arguments. Useful when your agent already knows which tool it wants.

Use `context_discover` with `mode: "execute"` before calling `context_execute`. Methods surfaced by `context_query` grounding or query-mode discovery are not necessarily direct-execute eligible.

| Parameter      | Type          | Required | Description                                 |
| -------------- | ------------- | -------- | ------------------------------------------- |
| `toolId`       | string (UUID) | Yes      | The marketplace tool ID                     |
| `toolName`     | string        | Yes      | The method name to call                     |
| `args`         | object        | No       | Arguments for the method                    |
| `sessionId`    | string (UUID) | No       | Execution session for spend tracking        |
| `maxSpendUsd`  | string        | No       | Cap spend for this session                  |
| `closeSession` | boolean       | No       | Close the execution session after this call |

### context\_discover

Search the marketplace to find tools before querying or executing.

`context_discover` is free marketplace retrieval. It returns tool IDs plus `mcpTools` method metadata, but it does not run the managed selector used by `context_query` Auto Mode. Use it for catalog inspection, Manual Mode pinning, or direct execution prep. Do not call it first for a normal question just because the question mentions a provider name.

| Parameter       | Type                     | Required | Description                                                          |
| --------------- | ------------------------ | -------- | -------------------------------------------------------------------- |
| `query`         | string                   | No       | Search term                                                          |
| `limit`         | number                   | No       | Max results (1–20, default 10)                                       |
| `mode`          | `"query"` \| `"execute"` | No       | Filter by mode                                                       |
| `favoritesOnly` | boolean                  | No       | Override the account-level Favorites-Only Auto Mode for this request |

***

## Example Workflows

### Simple Q\&A (Auto Mode)

Tell your agent:

> Use context\_query to find out which Kalshi markets have the highest open interest today.

The runtime discovers relevant tools, handles execution end-to-end, and returns a complete answer.

### Pinned Tools (Manual Mode)

For more control, first call `context_discover`, choose the relevant tool IDs, then call `context_query` with `toolIds`. Context still handles execution, grounding, and response assembly, but it stays within your pinned tool shortlist.

Use this only when pinning is intentional. If the user simply asks "using Crypto Positioning and Crypto Data" as part of a natural-language analysis request, put that provider constraint in the `question` and keep Auto Mode.

### Recurring Agent Routine

For daily reports, alerts, and repeated analyst jobs:

1. Start with Auto Mode `context_query` to find a good question shape.
2. Capture a Routine Recipe from the terminal structured result, including the exact question, assumptions, and `toolsUsed` names and IDs. Do not fetch `dataUrl` just to find tool IDs.
3. Switch to `responseShape: "evidence_only"` and `includeDataUrl: true` when your host agent writes the report.
4. Pin saved `toolsUsed` IDs as `toolIds` in `context_query` when the routine should stay within the same tool shortlist.
5. Use `context_execute` only if `context_discover` with `mode: "execute"` returns an eligible method.

See [Agent Data Routines](/sdk/agent-routines) for a copy-paste routine prompt. TypeScript users can adapt the runnable SDK example at [`examples/client/src/agent-routine.ts`](https://github.com/ctxprotocol/sdk/blob/main/examples/client/src/agent-routine.ts) in the [`examples/client`](https://github.com/ctxprotocol/sdk/tree/main/examples/client) package.

For Crypto Data order-flow routines, it is normal for Execute discovery to return no eligible methods. In that case, keep the routine on pinned Query with `responseShape: "evidence_only"` and `includeDataUrl: true`.

### Discovery -> Execute (agent-driven loop)

For full control, your agent can:

1. Call `context_discover` with a search query
2. Inspect the returned tools and methods
3. Call `context_execute` with the chosen tool and arguments
4. Synthesize the structured result into an answer

This mirrors the [Agentic Pattern](/sdk/agentic-pattern) but through MCP instead of the SDK.

***

## Pricing

MCP requests use the same pricing as the SDK:

* **Query**: pay-per-response (selector model + agent model + invoked tool costs)
* **Execute**: pay-per-call (method-level pricing set by tool builders)
* **Discover**: free

Your wallet balance and spending cap apply identically.

***

## Troubleshooting

<AccordionGroup>
  <Accordion title="401 Unauthorized">
    Ensure your `Authorization` header uses the format `Bearer sk_live_...`. Keys are generated at [ctxprotocol.com/settings](https://ctxprotocol.com).
  </Accordion>

  <Accordion title="Tools not appearing in Cursor">
    Check that `mcp.json` is valid JSON and the `url` field points to `https://www.ctxprotocol.com/api/mcp`. Restart Cursor after saving.
  </Accordion>

  <Accordion title="Session expired">
    Sessions expire after 30 minutes of inactivity. Your MCP client will re-initialize automatically on the next request.
  </Accordion>

  <Accordion title="Query returns capability_miss">
    No marketplace tool can satisfy the request. Rephrase to target a supported venue or capability, or check the suggested rewrites in the response.
  </Accordion>
</AccordionGroup>
