# Native MCP

Knowledge serves MCP `2026-07-28` using the official Rust SDK `rmcp 3.9.0`. MCP and OpenAPI 3.2.1 run alongside each other over the same SQLite index, OKF sources, retrieval engine, and access policies. [Core specification](https://modelcontextprotocol.io/specification/2026-07-28) · [SDK release](https://github.com/modelcontextprotocol/rust-sdk/releases/tag/rmcp-v3.9.0)

## Configuration

The default Rust feature set and `scripts/build.py` include `mcp`. An HTTP-model-only build can use `cargo build --locked --no-default-features --features mcp,sqlcipher`. The sample `knowledge.yml` shows the opt-in MCP settings. Use these groups under the existing `server` block. Retain its TLS and credential settings. The [MCP sample profile](https://github.com/tsok-org/source-code/blob/main/apps/knowledge/configs/mcp.yml) includes a complete local TLS example.

```yaml
server:
  mcp:
    http:
      enabled: true
      # oauth_resource: https://knowledge.example/mcp
      # oauth_only: true
    stdio:
      prefixes: [engineering/public]
    features:
      skills: true
      apps: true
      subscriptions: true
      authoring: false
      tasks: false
      context_tasks: true
    limits:
      payload_bytes: 262144
      subscription_streams: 8
      subscription_lifetime_secs: 300
      subscription_poll_ms: 2000
      task_ttl_secs: 86400
      task_poll_ms: 1000
      context_task_capacity: 32
      context_tasks_per_principal: 8
    # tools:
    #   allow: [retrieve, context, evidence]
```

| Group | Settings and defaults |
|---|---|
| `http` | `enabled` defaults to false. `oauth_resource` binds tokens to a canonical HTTPS `/mcp` URL. `oauth_only` defaults to false and requires an OAuth resource when enabled. An optional `server_card` declares a public `name`, `url` and `description`. |
| `stdio` | Optional. Configure `prefixes` to grant component-matched read access. An explicit `[""]` grants read access to the whole bundle. |
| `features` | All default to false. `skills` loads two built-in workflows. `apps` enables the cited-context viewer for capable clients. `subscriptions` enables updates to the visible catalog. `authoring` also requires `server.allow_source_writes` and the caller's `write` capability. Captures require `capture`. `tasks` tracks source publication and requires HTTP authoring. `context_tasks` enables read-only task retrieval on the configured transports. |
| `tools` | An optional `allow` list narrows the tools exposed by the configured features and the caller's permissions. |
| `limits` | `payload_bytes` defaults to 262144 (4 KiB–4 MiB). Core subscriptions default to 16 streams, 300 seconds lifetime and 2000 ms between reads. Task handles default to 86400 seconds retention and a 1000 ms suggested polling interval. `context_task_capacity` bounds retained context tasks across principals in one database (default 32, range 1–128). `context_tasks_per_principal` limits one principal’s share of that capacity (default 8, range 1–128). |
| `skill_catalog` | Optional `entries` with `directory`, additional relative `files` and `required_prefixes`. Each entry always includes `SKILL.md`. |
| `interaction` | Optional context query form with `clarify_context_query`, a private `state_key` and `ttl_secs` (default 180). |
| `events` | Optional experimental delivery with a private `cursor_key`, `poll`, `push` and `webhooks` groups. See [MCP Events](#mcp-events-sep-3415). |

Earlier flat beta settings remain accepted. Use either grouped or flat keys for each section.

The shared `server.max_body_bytes` limits MCP HTTP messages and inbound stdio lines. The request rate, work concurrency, and query and context budgets come from the existing server settings. Native work holds a slot until it finishes, even when a client disconnects or stops waiting.

## Connect

Start `knowledge --config /absolute/path/knowledge.yml serve` after configuring TLS and indexing the OKF bundle. Give a modern client the URL `https://localhost:8443/mcp`, the generated CA or the deployment CA, and a scoped bearer credential. Keep `/openapi.json` available for HTTP clients. Streamable HTTP uses per-request version, client identity, capabilities, and the routing headers defined for this revision. Discover with `server/discover`. [Streamable HTTP binding](https://modelcontextprotocol.io/specification/2026-07-28/basic/transports/streamable-http)

To verify discovery over the sample HTTPS listener, run this from the repository root.

```sh
curl --fail-with-body --silent --show-error \
  --cacert .knowledge-secure/secrets/ca.pem \
  -H "Authorization: Bearer $(cat .knowledge-secure/secrets/read.token)" \
  -H 'Content-Type: application/json' \
  -H 'Accept: application/json, text/event-stream' \
  -H 'MCP-Protocol-Version: 2026-07-28' \
  -H 'Mcp-Method: server/discover' \
  --data '{
    "jsonrpc": "2.0",
    "id": 1,
    "method": "server/discover",
    "params": {
      "_meta": {
        "io.modelcontextprotocol/protocolVersion": "2026-07-28",
        "io.modelcontextprotocol/clientInfo": {"name": "discovery-smoke-test", "version": "1"},
        "io.modelcontextprotocol/clientCapabilities": {}
      }
    }
  }' https://localhost:8443/mcp
```

For a local MCP client with stdio support, use this server entry after configuring `stdio.prefixes`.

```json
{
  "command": "/absolute/path/to/knowledge",
  "args": ["--config", "/absolute/path/to/knowledge.yml", "mcp-stdio"]
}
```

The stdio process uses the existing database and configured model roles for retrieval. If context tasks are enabled, it also writes to the task journal. Run `serve` or `watch` separately to keep it indexed. The process reserves stdout for newline-delimited JSON-RPC. OS permissions still govern whether the process can open the database and its key.

## Tool and resource surface

| Tool | Result |
|---|---|
| `retrieve` | Ranked OKF evidence with publication and citation references. Accepts lexical, vector, or hybrid mode, filters, graph traversal and configured reranking. |
| `context` | Bounded cited context using the same retrieval options. |
| `context_task` | Durable, cancellable cited context. With an empty query, requests a search term through a task form. |
| `select` | Authorized publication entries with filters and a cursor. |
| `evidence` | A local evidence record with its source version and locator. |
| `federated_retrieve`, `federated_context`, `federated_evidence` | Federated retrieval and qualified citations. These tools are listed when federation is enabled. Mount permissions continue to apply. |
| `changes`, `operation` | Submit or inspect an authorized OKF source operation. Enabled for the HTTP write scope. |

Use `tools/list` for the input and output JSON Schemas. When upgrading, remove the old `knowledge_` prefix from client tool calls and from `server.mcp.tools.allow` entries. Resource URIs, prompts and skill IDs keep their existing names. List resources to find `knowledge://<bundle>/catalog`. It returns the first 50 visible publication entries. Use `select` for more pages. Read local citations at `knowledge://<bundle>/evidence/<id>`. Resolve federated citations with the federated evidence tool.

`prompts/list` offers `cited-answer`, `evidence-review`, and `research`. Each accepts a `question` and optional `mode`. `completion/complete` suggests values for `mode`. The host runs the prompt workflow with Knowledge tool results as evidence.

## Skills, subscriptions and tasks

- **Skills** exposes `skills/list`, `skills/get`, `resources/directory/read` and manifest file reads. Built-in workflows cover retrieval and citation review. Operator entries load the explicit files at startup, with a 64 KiB per-file and 2 MiB total asset budget. Manifests include SHA-256 and byte size. Configure `required_prefixes` to limit a workflow to principals who can see every listed OKF prefix. [Skills extension](https://modelcontextprotocol.io/extensions/skills/overview)
- **Subscriptions** accepts the catalog URI in `subscriptions/listen`. The stream acknowledges the accepted filter and emits `notifications/resources/updated` when the visible catalog changes. It uses a separate bounded slot and closes at its configured lifetime or at OAuth token expiry, whichever comes first. Reopen and reread the catalog after reconnecting. [Resources specification](https://modelcontextprotocol.io/specification/2026-07-28/server/resources)
### Durable tasks

Declare `io.modelcontextprotocol/tasks` in the request's client capabilities. Follow the returned `taskId` with `tasks/get`, respecting `pollIntervalMs`. Both task workflows use the SQLite journal. [Tasks specification](https://modelcontextprotocol.github.io/ext-tasks/specification/2026-07-28/tasks.html)

- **Cited context** uses `features.context_tasks` and the `context_task` tool. A complete query can run immediately. An empty query requires form elicitation capability. Read the form in `inputRequests.query` and submit `inputResponses.query` through `tasks/update`. An accepted form looks like `{"action":"accept","content":{"query":"calibration frequency"}}`. Decline or cancel to end the task. Knowledge reauthorizes every call against the original principal and scope. Reconnect and poll with the same identity to resume a pending task after a restart. Work interrupted by a crash is eligible to resume when its lease expires. A resumed job uses the active retrieval and model configuration. Set a publication selector in the search parameters if the job must target a specific index publication.
- **Source publication** uses `features.tasks` and the `changes` tool. Retry the submission with the same idempotency key. The task starts after the source write commits. Publication requires an indexing worker and can continue after `tasks/cancel` acknowledges the client's intent. Use `operation` to diagnose source or indexing failures.

Context work shares `server.max_parallel_requests` with other tool work. A task without a free slot stays queued and a subsequent poll can start it. Cancellation prevents publication of a context result while an already-running model call may continue to hold its slot. `server.request_timeout_secs` bounds the time until a running task is marked failed. The slot is held until inference returns. Context-task capacity includes completed, failed and cancelled tasks until their TTL expires. A new submission prunes expired rows. The task journal inherits the SQLite encryption configuration.

## OAuth and enterprise integration

Set `server.mcp.http.oauth_resource` to the canonical public HTTPS endpoint. Configure a trusted issuer in `server.oauth.issuers` with that exact URL as its `audience`. Match the required subject or client ID and OAuth scopes to least-privilege Knowledge capabilities and OKF paths. Knowledge publishes `/.well-known/oauth-protected-resource/mcp`, includes the URL in its bearer challenge, and accepts those audience-bound access tokens only on `/mcp`. Local and scoped static bearer credentials can also authenticate under their existing policies unless `server.mcp.http.oauth_only` is enabled. An optional Server Card at `/mcp/server-card` exposes the configured public identity and transport metadata. [MCP authorization](https://modelcontextprotocol.io/specification/2026-07-28/basic/authorization) · [Knowledge issuer configuration](https://tsok.org/knowledge/docs/federation-security/)

With an authorization server that supports Client Credentials, register the service principal there and have it request a token scoped to the MCP resource. For Enterprise-Managed Authorization, the enterprise IdP issues the ID-JAG and the Resource Authorization Server exchanges it for a resource-bound access token. Knowledge validates the final access token at its resource boundary. Both grants were exercised through the official TypeScript client, a local TLS IdP fixture, and a separate local TLS authorization server fixture. Tenant registration, grant policy, and claim mappings still need validation with the deployment’s actual identity provider. [Client Credentials](https://modelcontextprotocol.io/extensions/auth/oauth-client-credentials) · [Enterprise-Managed Authorization](https://modelcontextprotocol.io/extensions/auth/enterprise-managed-authorization)

## Apps and context clarification

With `features.apps` and a client that declares the MCP Apps MIME type, `context` links to a read-only evidence viewer. The view uses the host's sandbox bridge and renders citation data as text. Plain structured tool results remain available for clients that use text or JSON.

With `interaction.clarify_context_query` enabled, a `context` call with an empty query can return a form to a client that declares form elicitation. The client retries the same request with the sealed state and the form result. Knowledge validates the expiry, scope and original arguments and runs retrieval under the current access rules. Use a random 32-byte state key stored as 64 hex characters in a private file or referenced environment variable.

## MCP Events (SEP-3415)

This opt-in profile follows the pinned draft `b08e4f9`. Knowledge publishes a source event only when a version enters or leaves the searchable publication. Operation events require write access and are filtered by owner and path scope. Consumers can discover schemas with `events/list`, then poll with an opaque cursor or open an opted-in push stream. [Pinned draft](https://github.com/pja-ant/modelcontextprotocol/blob/b08e4f9dd684f39d846d94089487fbeb28e666f5/seps/0000-events-extension.md)

```yaml
server:
  mcp:
    events:
      enabled: true
      cursor_key: {file: secrets/mcp-events.key}
      poll:
        max_events: 32
        max_scan_rows: 512
        max_replay_age_secs: 86400
        interval_ms: 2000
      push:
        enabled: true
        max_streams: 4
        lifetime_secs: 300
        heartbeat_secs: 15
```

Set the cursor key to a random 32-byte secret in hex. Keep it stable across restarts and separate from bearer and database secrets. Key rotation invalidates existing cursors and changes event IDs. Bindings cover the principal's access, bundle, event type and filter. Omit the cursor or pass `null` to start at the current position. Persist the returned cursor and deduplicate by event ID. Replay windows apply per delivery. Long streams use a separate quota and close no later than the token's expiry. Event-catalog changes across a restart are discovered by calling `events/list` again.

### Signed webhooks

Opt in to webhook delivery with an explicit list of receiver URLs. Configure each approved HTTPS URL and its pinned IP address. An enrollment authorizes delivery only for the listed Knowledge principal names. The configured allowlist is the endpoint's verification mechanism. Operators should confirm receiver consent before enrollment. The request cannot supply alternate hosts, ports, paths or addresses. Each delivery uses the pinned address, TLS validation for the URL hostname and a client with redirects and proxies disabled. [Draft endpoint verification rules](https://github.com/pja-ant/modelcontextprotocol/blob/b08e4f9dd684f39d846d94089487fbeb28e666f5/seps/0000-events-extension.md#webhook-security)

```yaml
server:
  mcp:
    events:
      # Existing enabled and cursor_key settings are required.
      webhooks:
        max_subscriptions: 16
        ttl_secs: 300
        timeout_secs: 5
        max_attempts: 3
        # Optional Ed25519 server identity. Requires http.server_card.
        signing:
          key_id: knowledge-events-2026-11
          seed: {file: secrets/mcp-webhook-ed25519.key}
          # previous_keys:
          #   - key_id: knowledge-events-previous
          #     public_key: <base64url-without-padding Ed25519 public key>
        targets:
          - url: https://events.example.org/knowledge
            address: 192.0.2.10 # Replace with your receiver's approved address.
            principals: [events-consumer]
            # ca_file: secrets/receiver-ca.pem
```

The authenticated client supplies a Standard Webhooks secret in `events/subscribe`. Knowledge holds it in memory, uses HMAC over the exact request bytes and keeps the same delivery ID across retries. Acknowledged or abandoned deliveries advance the watermark. Replay gaps have a signed control message. Keep the returned cursor and renew before `refreshBefore`. After a restart, renew with the last stored cursor. `events/unsubscribe` cancels future deliveries for that subscription. Use distinct secrets per receiver and keep the Events cursor key stable if you need IDs across restarts.

Optional `webhooks.signing` appends an Ed25519 `v1a,` signature to the `v1,` HMAC header on every attempt. Provision a separate random 32-byte seed as 64 hexadecimal characters in a private file or environment variable. Enable `http.server_card` and configure its URL to match the HTTPS MCP endpoint. Fetch `/mcp/server-card` from that authenticated HTTPS origin and read the matching remote's `extensions["io.modelcontextprotocol/events"].webhooks.signingKeys` JWK set. Verify the Ed25519 signature against the trusted public keys over the exact `webhook-id.timestamp.body` bytes. Independently verify HMAC, check timestamp freshness, and deduplicate by delivery ID. [Pinned draft signing profile](https://github.com/pja-ant/modelcontextprotocol/blob/b08e4f9dd684f39d846d94089487fbeb28e666f5/seps/0000-events-extension.md#webhook-security)

For rotation, use a new `key_id` and private seed and retain the outgoing public key in `previous_keys` for the receiver's refresh and retry window. Up to four extra public keys are allowed. The server signs with one active Ed25519 key. Receivers can try the published keys because the `v1a,` signature does not include a key ID. Refresh the card before switching and retain old keys until in-flight messages have settled.

## Coverage

The Events type catalog is static for a running server. The optional `eventsListChanged` field and notification are pending support for extension filters, their acknowledgment, and custom subscription notifications in the Rust SDK. Core resource subscriptions cover changes to visible OKF entries. See the [validation results](https://github.com/tsok-org/source-code/blob/main/apps/knowledge/docs/mcp-validation.md) and [capability plan](https://github.com/tsok-org/source-code/blob/main/apps/knowledge/docs/mcp-plan.md).
