TypeScript SDK

KYA-OS TypeScript SDK — @kya-os/mcp package documentation

@kya-os/mcp

The TypeScript reference implementation for KYA-OS. Identity, delegation, and cryptographic proofs for the Model Context Protocol.

Installation

npm install @kya-os/mcp

Requires Node.js 20+. Peer dependency on @modelcontextprotocol/sdk (optional, only needed for withKyaOs).


The v1 Model: Per-Request Proofs

The ratified v1 model is stateless at its core: every request carries its own material, and every response carries its own proof. There is no session to establish and no handshake to run first, so any request can land on any server instance.

The proofs ride reverse-DNS keys in MCP _meta:

CarrierKeyContents
Request proof_meta["org.kya-os/request-proof"]The self-contained, sender-constrained holder-of-key proof; its prf field names the profile org.kya-os/proof.v1
Response proof_meta["org.kya-os/response-proof"]The detached JWS ({ jws, meta }) signed by the server over the canonical response content

withKyaOs — One-Line Integration

Wraps an existing MCP server with identity and proofs — the same call the Quick Start begins with:

import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { withKyaOs, NodeCryptoProvider } from "@kya-os/mcp";

const server = new McpServer({ name: "my-server", version: "1.0.0" });
const kyaos = await withKyaOs(server, { crypto: new NodeCryptoProvider() });

// Your server now has:
// - A DID identity (kyaos.identity.did)
// - A signed proof on every tool response (_meta["org.kya-os/response-proof"])
// - Per-request verification with replay prevention

Register tools exactly like you normally would — KYA-OS operates at the protocol layer.

The MCP Extension: org.kya-os/decentralized-authority

KYA-OS binds to MCP 2026-07-28 extension negotiation (SEP-2133) under the extension id org.kya-os/decentralized-authority. The negotiation surface is exported from the package root:

import {
  KYA_OS_EXTENSION_ID,   // "org.kya-os/decentralized-authority"
  buildExtensionsEntry,  // capability declaration for server/client
  requireExtension,      // per-request admission gate
} from "@kya-os/mcp";

In required mode, requireExtension rejects a non-declaring client with the core -32021 error carrying requiredCapabilities; discovery and ping are exempt from the gate. Everything is strictly additive — nothing runs unless the host opts in.


Core API

createKyaOsMiddleware — Low-Level Control

For when you need full control over identity lifecycle and tool wrapping.

import {
  createKyaOsMiddleware,
  generateIdentity,
  NodeCryptoProvider,
} from "@kya-os/mcp";

const crypto = new NodeCryptoProvider();
const identity = await generateIdentity(crypto);
const kyaos = createKyaOsMiddleware(
  { identity, session: { sessionTtlMinutes: 60 } },
  crypto
);

wrapWithProof — Automatic Proof Attachment

Wraps a tool handler so every response includes a detached JWS signature.

const search = kyaos.wrapWithProof("search", async (args) => ({
  content: [{ type: "text", text: `Results for: ${args["query"]}` }],
}));

Wraps a tool handler so it requires a valid delegation VC before executing.

const placeOrder = kyaos.wrapWithDelegation(
  "place_order",
  {
    scopeId: "orders:write",
    consentUrl: "https://example.com/consent",
  },
  kyaos.wrapWithProof("place_order", async (args) => ({
    content: [{ type: "text", text: `Order placed: ${args["item"]}` }],
  }))
);

If the agent doesn't have a valid delegation, the tool returns a signed needs_authorization challenge with the consent URL. The human approves, the agent gets a VC, and retries — the consent step-up of SPEC.md §9.

generateIdentity — Create a DID

Generates an Ed25519 key pair and derives a did:key identifier.

import { generateIdentity, NodeCryptoProvider } from "@kya-os/mcp";

const crypto = new NodeCryptoProvider();
const identity = await generateIdentity(crypto);

console.log(identity.did);
// did:key:z6Mk...

Modules

The package exposes its full surface as subpath exports (from the SSOT package.json exports map):

ImportWhat it does
@kya-os/mcpMain entry. withKyaOs, createKyaOsMiddleware, generateIdentity, providers, extension negotiation (KYA_OS_EXTENSION_ID, requireExtension, buildExtensionsEntry), verifyOrHints, policy + audit re-exports.
@kya-os/mcp/cardEntity Card: card() builder, buildCard / resolveCard / verifyCard, withKyaOsCard + requireProof middleware, per-request org.kya-os/proof.v1 mint/verify, card-era (VC 2.0 + ZCAP-LD) delegation chain evaluation, CIMD on-ramp.
@kya-os/mcp/delegationLegacy-era (VC 1.0) credential issue/verify, DID resolution (did:key, did:web), StatusList2021 + Bitstring managers, cascading revocation, scope attenuation, outbound headers/proof.
@kya-os/mcp/authHandshake validation primitives for the legacy session profile.
@kya-os/mcp/proofGenerate and verify detached JWS proofs with canonical hashing (JCS + SHA-256).
@kya-os/mcp/sessionLegacy session manager (see the legacy section below).
@kya-os/mcp/providersAbstract CryptoProvider, storage, clock, and fetch providers; NodeCryptoProvider, WebCryptoProvider, memory implementations.
@kya-os/mcp/loggingStructured logger seam.
@kya-os/mcp/typesPure TypeScript protocol interfaces.
@kya-os/mcp/middlewareThe withKyaOs server middleware and its transport wrapper.
@kya-os/mcp/policyPolicy engine: classification, approval requirements, projections.
@kya-os/mcp/authzAuthorization-service adapters (OIDC/PKCE, pending-flow store, requirements).
@kya-os/mcp/auditVerifiable auditability protocol: events, recorder, receipts, Merkle checkpoints, replay bundles, kya-audit CLI.
@kya-os/mcp/audit/testingExecutable provider contract kit for custom audit backends.
@kya-os/mcp/cheqdCheqdStatusListResolver — on-chain StatusList2021 revocation checks against cheqd DID-Linked Resources.
@kya-os/mcp/schemas/*.jsonThe 19 published JSON Schemas (delegation credentials, detached proof, card, handshake, audit family, extension settings, well-known-mcpi.json).
@kya-os/mcp/package.jsonPackage metadata (exports map, version).

There is no ./extension subpath: the org.kya-os/decentralized-authority negotiation surface is exported from the package root.


Legacy Session Surface (Read-Compat)

withKyaOs still registers the _kyaos protocol tool by default so legacy clients can run the session handshake:

await withKyaOs(server, {
  crypto: new NodeCryptoProvider(),
  handshakeExposure: "none",   // 'tool' (default) | 'none' — omit the _kyaos tool
  autoSession: false,           // skip automatic session creation
});

If your runtime has its own connection lifecycle, disable tool exposure and drive the legacy flow directly:

const kyaos = await withKyaOs(server, {
  crypto: new NodeCryptoProvider(),
  handshakeExposure: "none",
  autoSession: false,
});

// In your runtime's connection hook (legacy session establishment):
await kyaos.handleKyaOs({
  action: "handshake",
  nonce: "client-generated-nonce",
  audience: kyaos.identity.did,
  timestamp: Math.floor(Date.now() / 1000),
  agentDid: "did:key:...optional...",
});

@kya-os/mcp/session exposes the session manager behind this flow (nonce handshake, session TTL, replay prevention) for hosts that embed it directly.


Extension Points

Every cryptographic operation, storage backend, and DID resolution method is abstracted behind interfaces you implement.

Custom Crypto Provider

import { CryptoProvider } from "@kya-os/mcp";

class KMSCryptoProvider extends CryptoProvider {
  async sign(data: Uint8Array, keyArn: string) {
    return kmsClient.sign({ KeyId: keyArn, Message: data });
  }
}

await withKyaOs(server, { crypto: new KMSCryptoProvider() });

Custom Nonce Cache

import { NonceCacheProvider } from "@kya-os/mcp";

class RedisNonceCacheProvider extends NonceCacheProvider {
  async hasNonce(nonce: string) {
    return redis.exists(`nonce:${nonce}`);
  }
  async addNonce(nonce: string, ttl: number) {
    redis.setex(`nonce:${nonce}`, ttl, "1");
  }
}

DID Resolution

Built-in support for did:key (self-resolving) and did:web (HTTP resolution through the SSRF-hardened SafeFetch). Add any custom method via the DID resolver registry.


Conformance Levels

Three levels, progressively deeper trust guarantees:

LevelWhat's required
Level 1 — Core CryptoEd25519 signatures, DID:key resolution, JCS canonicalization
Level 2 — Full SessionLevel 1 + nonce-based handshake, session management, replay prevention
Level 3 — Full DelegationLevel 2 + W3C VC issuance/verification, scope attenuation, StatusList2021, cascading revocation

Full details in CONFORMANCE.md.


Examples

ExampleWhat it shows
consent-basicHuman-in-the-loop consent: needs_authorization → consent page → delegation VC → execution
consent-fullFull consent flow with a production-style consent UI
consent-persistencePersisting grants across restarts
entity-cardPublishing and resolving an Entity Card with per-request proofs
node-serverLow-level Server API with proofs and restricted tools
brave-searchReal MCP server (Brave Search) wrapped with KYA-OS
outbound-delegationForwarding delegation context to downstream services
verify-proofStandalone proof verification
audit-trailVerifiable audit trail walkthrough
statuslistStatus-list revocation mechanics
revokedOn-chain revocation via cheqd (DEF CON "REVOKED" demo)
context7-with-kya-osAdding KYA-OS to an existing server with withKyaOs