Skip to content
Merged
5 changes: 5 additions & 0 deletions docs/contributing/adding-capabilities.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,11 @@ domains synthesized from outbound WebSocket connectors (see
Those domains are driven by MCP **`remoteConnectors`** rather than by editing
`builtinDomains` in-repo.

**MCP client servers:** the same runtime merge also synthesizes `mcp:<server>`
domains from the user's enabled MCP servers (see
[`architecture/mcp-client-servers.md`](./architecture/mcp-client-servers.md)),
driven by the `mcp_server_settings` D1 table and per-user hub snapshots.

`defineCapability()` in
`packages/worker/src/mcp/capabilities/define-capability.ts` normalizes Zod →
JSON Schema and wraps handlers with logging; domain helpers call it for you.
Expand Down
3 changes: 3 additions & 0 deletions docs/contributing/architecture/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@ to become.
same PR whenever a primitive is added, removed, or reshaped.
- [Remote connectors](./remote-connectors.md): generic outbound WebSocket
protocol, URLs, secrets, and MCP caller context for any `kind` / instance.
- [MCP client servers](./mcp-client-servers.md): user-added remote MCP servers
Kody connects to as a client (per-user hub Durable Object, OAuth flow, and
`kody.mcp[...]` capability synthesis).
- [Local Agent Bridge Direction](./local-agent-bridge.md): proposed direction
for securely reaching local-network systems through an outbound agent
connection.
Expand Down
85 changes: 85 additions & 0 deletions docs/contributing/architecture/mcp-client-servers.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
# MCP client servers (user-added MCP servers)

Kody can act as an **MCP client** to remote MCP servers a user adds. Tools
discovered on those servers become synthesized capability domains callable from
execute via `kody.mcp["<server-name>"].<tool>(input)`. This is the inverse of
the `/mcp` endpoint (where Kody is the server) and complements remote connectors
(which dial in to Kody over WebSockets): MCP client servers are **remote-only**
— Kody dials out over HTTP using the Agents SDK `MCPClientManager`.

## Components

- **`McpClientHub` Durable Object** (`packages/worker/src/mcp-client/hub.ts`) —
one per user, id derived from the stable MCP `userId`. Owns the Agents SDK
`MCPClientManager`, which persists registered servers, OAuth client
registrations, and tokens in the DO's SQLite storage. Exposes RPC methods:
`addServer`, `reconnectServer`, `refreshServer`, `removeServer`,
`handleOAuthCallback`, `getSnapshot`, `callTool`, and
`purgeForAccountDeletion`.
- **D1 `mcp_server_settings` table**
(`packages/worker/migrations/0053-mcp-server-settings.sql`) — user-scoped
metadata (id, name, url, enabled). D1 answers "which servers does this user
have enabled" without waking the DO; the DO owns live connection state and
tokens.
- **Hub client with snapshot cache**
(`packages/worker/src/mcp-client/hub-client.ts`) — worker-side facade over the
DO stub. Snapshots are cached per user for 30 seconds and invalidated on every
mutation.
- **Settings service** (`packages/worker/src/mcp-client/settings-service.ts`) —
validates names (`^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$`) and URLs (https
required; plain http allowed only for loopback hosts), and keeps D1 and the
hub DO in sync.

## OAuth flow

1. `addServer` registers the server with a callback URL of
`<app-origin>/account/mcp-servers/oauth/callback` and starts connecting.
2. If the server requires OAuth, the SDK performs dynamic client registration
and the connection parks in state `authenticating` with an `authUrl`.
3. The user opens `authUrl` in the browser (surfaced in the account UI and by
the `mcp_server_add` / `mcp_server_list` capabilities).
4. The provider redirects back to the callback route. The worker authenticates
the browser session cookie, forwards the full callback URL to that user's hub
DO, and the SDK exchanges the code (matching the `state` parameter to the
pending authorization) and establishes the connection.
5. The route redirects to `/account/mcp-servers?auth=success|error` for user
feedback. Tokens live only in the DO storage; they never reach D1 or the
client.

Because the callback is resolved through the session cookie, the OAuth state is
always looked up in the hub belonging to the signed-in user — cross-user
callback replay finds no matching state.

## Capability synthesis and invocation

- Registry: `getCapabilityRegistryForContext` loads enabled server refs from D1
and hub snapshots, then `synthesizeMcpServerToolDomain`
(`packages/worker/src/mcp/capabilities/mcp-server/index.ts`) creates a
`mcp:<server-name>` domain with a capability per discovered tool
(`mcp:<server-name>:<tool>`), marked `source: 'mcp-server'`.
- Execute: the `kody.mcp` proxy mirrors `kody.remote` — tools are called as
`kody.mcp["<server-name>"].<tool>(input)` and are never exposed as flat
`kody.*` functions. Search capability detail returns the exact accessor.
- Tool calls flow worker → hub DO `callTool` → `MCPClientManager.callTool` →
remote server. Structured content is returned directly when present.

## Management surfaces

- **UI**: `/account/mcp-servers` (add, authorize, reconnect, refresh tools,
enable/disable, remove; shows live state and discovered tools).
- **Capabilities**: the `mcp_servers` domain (`mcp_server_add`,
`mcp_server_list`, `mcp_server_reconnect`, `mcp_server_refresh`,
`mcp_server_remove`, `mcp_server_set_enabled`).

## Isolation and lifecycle

- Every path is scoped by `userId`: D1 rows, the hub DO id, and registry
synthesis. Account deletion purges the hub DO storage
(`purgeForAccountDeletion`) and deletes `mcp_server_settings` rows; account
export includes the settings rows.

## Related docs

- [Remote connectors](./remote-connectors.md) — the inbound-WebSocket
counterpart with the same naming pattern (`kody.remote[...]`).
- [Data storage](./data-storage.md) — D1 vs Durable Object storage split.
24 changes: 21 additions & 3 deletions docs/contributing/architecture/primitives.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -150,9 +150,9 @@ primitives:
name: Capability registry
summary:
Builtin capability domains (account, admin, apps, coding, community,
email, integrations, jobs, meta, packages, repo, secrets, services,
storage, values) merged with synthesized remote-connector domains behind
search/execute.
email, integrations, jobs, mcp_servers, meta, packages, repo, secrets,
services, storage, values) merged with synthesized remote-connector and
MCP server domains behind search/execute.
code:
- packages/worker/src/mcp/capabilities/
docs:
Expand Down Expand Up @@ -299,6 +299,24 @@ primitives:
docs:
- docs/contributing/architecture/remote-connectors.md

- id: mcp-client-servers
group: assistant
name: MCP client servers
summary:
User-added remote MCP servers Kody connects to as a client via the Agents
SDK MCPClientManager in the per-user McpClientHub Durable Object (OAuth
tokens in DO storage), with D1-backed settings, account UI at
/account/mcp-servers, the mcp_servers capability domain, and synthesized
mcp:<server> capability domains callable via kody.mcp[...].
code:
- packages/worker/src/mcp-client/
- packages/worker/src/mcp/capabilities/mcp-server/
- packages/worker/src/mcp/capabilities/mcp-servers/
- packages/worker/src/app/handlers/account-mcp-servers.ts
- packages/worker/migrations/0053-mcp-server-settings.sql
docs:
- docs/contributing/architecture/mcp-client-servers.md

- id: realtime-sessions
group: assistant
name: Realtime sessions
Expand Down
36 changes: 36 additions & 0 deletions packages/shared/src/mcp-servers.node.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { expect, test } from 'vitest'
import {
isValidMcpServerName,
normalizeMcpServerName,
validateMcpServerUrl,
} from './mcp-servers.ts'

test('MCP server names normalize to lowercase and validate the slug shape', () => {
expect(normalizeMcpServerName(' Linear ')).toBe('linear')
expect(isValidMcpServerName('linear')).toBe(true)
expect(isValidMcpServerName('my-server-2')).toBe(true)
expect(isValidMcpServerName('a')).toBe(true)

expect(isValidMcpServerName('')).toBe(false)
expect(isValidMcpServerName('-leading-dash')).toBe(false)
expect(isValidMcpServerName('trailing-dash-')).toBe(false)
expect(isValidMcpServerName('has space')).toBe(false)
expect(isValidMcpServerName('has_underscore')).toBe(false)
expect(isValidMcpServerName('x'.repeat(65))).toBe(false)
expect(isValidMcpServerName('x'.repeat(64))).toBe(true)
})

test('MCP server URLs require https except for loopback hosts', () => {
expect(validateMcpServerUrl('https://mcp.example.com/mcp')).toEqual({
ok: true,
url: 'https://mcp.example.com/mcp',
})
expect(validateMcpServerUrl(' https://mcp.example.com/mcp ').ok).toBe(true)
expect(validateMcpServerUrl('http://localhost:8787/mcp').ok).toBe(true)
expect(validateMcpServerUrl('http://127.0.0.1:8787/mcp').ok).toBe(true)

expect(validateMcpServerUrl('').ok).toBe(false)
expect(validateMcpServerUrl('not a url').ok).toBe(false)
expect(validateMcpServerUrl('http://example.com/mcp').ok).toBe(false)
expect(validateMcpServerUrl('ftp://example.com/mcp').ok).toBe(false)
})
50 changes: 50 additions & 0 deletions packages/shared/src/mcp-servers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
export type McpServerRef = {
serverId: string
name: string
}

export const mcpServerNamePattern = /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/

export function normalizeMcpServerName(name: string): string {
return name.trim().toLowerCase()
}

export function isValidMcpServerName(name: string): boolean {
return mcpServerNamePattern.test(normalizeMcpServerName(name))
}

const loopbackHostnames = new Set(['localhost', '127.0.0.1', '[::1]'])

/**
* Remote MCP servers must be reachable over HTTP(S). Plain HTTP is only
* allowed for loopback hosts so local development against a mock server works;
* anything else must use HTTPS. Private/internal addresses are additionally
* rejected at connect time by the Agents SDK MCP client.
*/
export function validateMcpServerUrl(url: string): {
ok: boolean
url?: string
error?: string
} {
const trimmed = url.trim()
if (!trimmed) {
return { ok: false, error: 'Server URL is required.' }
}
let parsed: URL
try {
parsed = new URL(trimmed)
} catch {
return { ok: false, error: 'Server URL must be a valid absolute URL.' }
}
if (parsed.protocol === 'https:') {
return { ok: true, url: parsed.toString() }
}
if (parsed.protocol === 'http:' && loopbackHostnames.has(parsed.hostname)) {
return { ok: true, url: parsed.toString() }
}
return {
ok: false,
error:
'Server URL must use https (plain http is only allowed for localhost).',
}
}
3 changes: 3 additions & 0 deletions packages/worker/client/app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,9 @@ export function App(handle: Handle<AppProps>) {
<a href="/account/remote-connectors" mix={css(primaryLinkCss)}>
Connectors
</a>
<a href="/account/mcp-servers" mix={css(primaryLinkCss)}>
MCP servers
</a>
{showAdminLink ? (
<a href="/admin/users" mix={css(primaryLinkCss)}>
Admin
Expand Down
Loading
Loading