Skip to content

A self-improving RLM agent for coding workflows and long-running autonomous tasks.

Rust

add mcp integrations for linear and notion (#280)

kt2706aa2e015b
diff --git a/packages/ai/package.json b/packages/ai/package.json
index b6a836b984..8b4229544c 100644
--- a/packages/ai/package.json
+++ b/packages/ai/package.json
@@ -46,6 +46,10 @@
"types": "./dist/oauth.d.ts",
"import": "./dist/oauth.js"
},
+ "./mcp": {
+ "types": "./dist/mcp.d.ts",
+ "import": "./dist/mcp.js"
+ },
"./bedrock-provider": {
"types": "./dist/bedrock-provider.d.ts",
"import": "./dist/bedrock-provider.js"
diff --git a/packages/ai/src/mcp.ts b/packages/ai/src/mcp.ts
new file mode 100644
index 0000000000..02908545da
--- /dev/null
+++ b/packages/ai/src/mcp.ts
@@ -0,0 +1 @@
+export * from "./mcp/index.js";
diff --git a/packages/ai/src/mcp/catalog.ts b/packages/ai/src/mcp/catalog.ts
new file mode 100644
index 0000000000..049b779cb2
--- /dev/null
+++ b/packages/ai/src/mcp/catalog.ts
@@ -0,0 +1,53 @@
+// Built-in MCP integrations we ship a skill package for. User servers go in the `mcpServers` setting instead.
+
+import { getOAuthProvider, registerOAuthProvider } from "../utils/oauth/index.js";
+import { createMcpOAuthProvider, type McpOAuthConfig } from "./oauth.js";
+
+export interface McpCatalogEntry {
+ /** Matches the skill package import name and the auth.json key `mcp:<server>`. */
+ server: string;
+ label: string;
+ url: string;
+ oauth?: Omit<McpOAuthConfig, "server" | "url"> & { kind: "oauth" };
+}
+
+export const BUILTIN_MCP_CATALOG: readonly McpCatalogEntry[] = [
+ {
+ server: "linear",
+ label: "Linear",
+ url: "https://mcp.linear.app/mcp",
+ oauth: { kind: "oauth", label: "Linear" },
+ },
+ {
+ server: "notion",
+ label: "Notion",
+ url: "https://mcp.notion.com/mcp",
+ oauth: { kind: "oauth", label: "Notion" },
+ },
+];
+
+export function getCatalogEntry(server: string): McpCatalogEntry | undefined {
+ return BUILTIN_MCP_CATALOG.find((entry) => entry.server === server);
+}
+
+/**
+ * Register the built-in catalog's OAuth providers. Idempotent. Must be called
+ * after any resetOAuthProviders() (e.g. ModelRegistry.refresh) since reset drops
+ * everything but the model-provider built-ins.
+ */
+export function registerBuiltinMcpOAuthProviders(): void {
+ for (const entry of BUILTIN_MCP_CATALOG) {
+ if (entry.oauth?.kind !== "oauth") continue;
+ const id = `mcp:${entry.server}`;
+ if (getOAuthProvider(id)) continue;
+ registerOAuthProvider(
+ createMcpOAuthProvider({
+ server: entry.server,
+ label: entry.label,
+ url: entry.url,
+ scopes: entry.oauth.scopes,
+ clientId: entry.oauth.clientId,
+ }),
+ );
+ }
+}
diff --git a/packages/ai/src/mcp/index.ts b/packages/ai/src/mcp/index.ts
new file mode 100644
index 0000000000..5d797ee0c3
--- /dev/null
+++ b/packages/ai/src/mcp/index.ts
@@ -0,0 +1,4 @@
+export type { McpCatalogEntry } from "./catalog.js";
+export { BUILTIN_MCP_CATALOG, getCatalogEntry, registerBuiltinMcpOAuthProviders } from "./catalog.js";
+export type { McpOAuthConfig } from "./oauth.js";
+export { createMcpOAuthProvider } from "./oauth.js";
diff --git a/packages/ai/src/mcp/oauth.ts b/packages/ai/src/mcp/oauth.ts
new file mode 100644
index 0000000000..092add6d2e
--- /dev/null
+++ b/packages/ai/src/mcp/oauth.ts
@@ -0,0 +1,380 @@
+// Generic OAuth 2.1 (PKCE + dynamic client registration) for remote MCP servers.
+// One provider per server, registered as `mcp:<server>` so it reuses auth.json. Node-only (callback server).
+
+import type { Server } from "node:http";
+import { oauthErrorHtml, oauthSuccessHtml } from "../utils/oauth/oauth-page.js";
+import { generatePKCE } from "../utils/oauth/pkce.js";
+import type { OAuthCredentials, OAuthLoginCallbacks, OAuthProviderInterface } from "../utils/oauth/types.js";
+
+const CALLBACK_HOST = process.env.PI_OAUTH_CALLBACK_HOST || "127.0.0.1";
+// A range (not one port) so a leaked/concurrent login can't wedge all logins with EADDRINUSE.
+// Distinct from the Anthropic callback port (53692). All candidates are registered as redirect URIs.
+const CALLBACK_PORT_BASE = Number(process.env.PI_MCP_OAUTH_CALLBACK_PORT || 53700);
+const CALLBACK_PORT_COUNT = 10;
+const CALLBACK_PATH = "/callback";
+const CALLBACK_PORTS = Array.from({ length: CALLBACK_PORT_COUNT }, (_, i) => CALLBACK_PORT_BASE + i);
+const redirectUriFor = (port: number) => `http://localhost:${port}${CALLBACK_PATH}`;
+const ALL_REDIRECT_URIS = CALLBACK_PORTS.map(redirectUriFor);
+const TOKEN_EXPIRY_BUFFER_MS = 5 * 60 * 1000;
+
+/** Authorization-server metadata we rely on (RFC 8414 / OAuth 2.1 + DCR). */
+interface AuthServerMetadata {
+ issuer?: string;
+ authorization_endpoint: string;
+ token_endpoint: string;
+ registration_endpoint?: string;
+ scopes_supported?: string[];
+}
+
+export interface McpOAuthConfig {
+ /** MCP server name; provider id becomes `mcp:<server>`. */
+ server: string;
+ /** Human label for UI. */
+ label?: string;
+ /** The MCP endpoint URL — discovery is rooted at its origin. */
+ url: string;
+ /** Pre-registered client id (servers without DCR, e.g. Slack). */
+ clientId?: string;
+ /** Explicit scopes; falls back to the server's advertised scopes. */
+ scopes?: string;
+}
+
+/** Extra fields we persist alongside the standard credential triple. */
+interface McpCredentials extends OAuthCredentials {
+ tokenEndpoint?: string;
+ clientId?: string;
+}
+
+async function fetchJson(url: string, init?: RequestInit): Promise<unknown> {
+ const res = await fetch(url, init);
+ if (!res.ok) {
+ throw new Error(`${init?.method ?? "GET"} ${url} failed: ${res.status} ${await res.text()}`);
+ }
+ return res.json();
+}
+
+/** Random, URL-safe CSRF `state` value, independent of the PKCE verifier. */
+function randomState(): string {
+ const bytes = new Uint8Array(32);
+ crypto.getRandomValues(bytes);
+ return btoa(String.fromCharCode(...bytes))
+ .replace(/\+/g, "-")
+ .replace(/\//g, "_")
+ .replace(/=/g, "");
+}
+
+/** Try the protected-resource and auth-server well-known docs at the URL's origin. */
+async function discover(url: string): Promise<AuthServerMetadata> {
+ const origin = new URL(url).origin;
+ const candidates = [
+ `${origin}/.well-known/oauth-authorization-server`,
+ `${origin}/.well-known/openid-configuration`,
+ ];
+ let lastError: unknown;
+ for (const candidate of candidates) {
+ try {
+ const meta = (await fetchJson(candidate)) as AuthServerMetadata;
+ if (meta.authorization_endpoint && meta.token_endpoint) {
+ return meta;
+ }
+ } catch (error) {
+ lastError = error;
+ }
+ }
+ throw new Error(
+ `Could not discover OAuth metadata for ${origin}. ` +
+ `Tried ${candidates.join(", ")}. Last error: ${String(lastError)}`,
+ );
+}
+
+/** Dynamic client registration (RFC 7591). Returns the issued client_id. */
+async function registerClient(registrationEndpoint: string, label: string): Promise<string> {
+ const body = {
+ client_name: label,
+ redirect_uris: ALL_REDIRECT_URIS,
+ grant_types: ["authorization_code", "refresh_token"],
+ response_types: ["code"],
+ token_endpoint_auth_method: "none",
+ };
+ const data = (await fetchJson(registrationEndpoint, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(body),
+ })) as { client_id?: string };
+ if (!data.client_id) {
+ throw new Error(`Dynamic client registration at ${registrationEndpoint} returned no client_id`);
+ }
+ return data.client_id;
+}
+
+type CallbackResult = { code: string; state: string } | null;
+
+async function startCallbackServer(label: string): Promise<{
+ server: Server;
+ redirectUri: string;
+ cancel: () => void;
+ waitForCode: () => Promise<CallbackResult>;
+}> {
+ const { createServer } = await import("node:http");
+ let settle: ((value: CallbackResult) => void) | undefined;
+ const waitPromise = new Promise<CallbackResult>((resolve) => {
+ let settled = false;
+ settle = (value) => {
+ if (!settled) {
+ settled = true;
+ resolve(value);
+ }
+ };
+ });
+
+ const handler = (req: import("node:http").IncomingMessage, res: import("node:http").ServerResponse) => {
+ const url = new URL(req.url || "", "http://localhost");
+ if (url.pathname !== CALLBACK_PATH) {
+ res.writeHead(404, { "Content-Type": "text/html; charset=utf-8" });
+ res.end(oauthErrorHtml("Callback route not found."));
+ return;
+ }
+ const error = url.searchParams.get("error");
+ const code = url.searchParams.get("code");
+ const state = url.searchParams.get("state");
+ res.writeHead(error || !code ? 400 : 200, { "Content-Type": "text/html; charset=utf-8" });
+ if (error) {
+ res.end(oauthErrorHtml(`${label} authentication failed.`, `Error: ${error}`));
+ settle?.(null);
+ return;
+ }
+ if (!code || !state) {
+ res.end(oauthErrorHtml("Missing code or state parameter."));
+ settle?.(null);
+ return;
+ }
+ res.end(oauthSuccessHtml(`${label} authentication completed. You can close this window.`));
+ settle?.({ code, state });
+ };
+
+ // Try each candidate port with a FRESH server (a server that failed to listen
+ // can't be reused), so a leaked/concurrent login can't block us with EADDRINUSE.
+ let lastError: unknown;
+ for (const port of CALLBACK_PORTS) {
+ const server = createServer(handler);
+ // Persistent handler so a post-bind 'error' is never an unhandled crash.
+ let bindErr: ((err: unknown) => void) | undefined;
+ server.on("error", (err) => bindErr?.(err));
+ try {
+ const bound = await new Promise<boolean>((resolve) => {
+ bindErr = () => resolve(false);
+ server.listen(port, CALLBACK_HOST, () => {
+ bindErr = undefined;
+ resolve(true);
+ });
+ });
+ if (bound) {
+ return {
+ server,
+ redirectUri: redirectUriFor(port),
+ cancel: () => settle?.(null),
+ waitForCode: () => waitPromise,
+ };
+ }
+ lastError = `port ${port} in use`;
+ server.close();
+ } catch (err) {
+ lastError = err;
+ server.close();
+ }
+ }
+ throw new Error(
+ `Could not start the OAuth callback server: ports ${CALLBACK_PORT_BASE}-${
+ CALLBACK_PORT_BASE + CALLBACK_PORT_COUNT - 1
+ } are all in use. Close other login attempts and retry. (${String(lastError)})`,
+ );
+}
+
+function parseRedirectInput(input: string, expectedState: string): { code: string; state: string } {
+ const value = input.trim();
+ let code: string | undefined;
+ let state: string | undefined;
+ try {
+ const url = new URL(value);
+ code = url.searchParams.get("code") ?? undefined;
+ state = url.searchParams.get("state") ?? undefined;
+ } catch {
+ const params = new URLSearchParams(value);
+ code = params.get("code") ?? value;
+ state = params.get("state") ?? undefined;
+ }
+ if (state && state !== expectedState) {
+ throw new Error("OAuth state mismatch");
+ }
+ if (!code) {
+ throw new Error("Missing authorization code");
+ }
+ return { code, state: state ?? expectedState };
+}
+
+async function exchangeToken(
+ tokenEndpoint: string,
+ params: Record<string, string>,
+): Promise<{ access_token: string; refresh_token?: string; expires_in?: number }> {
+ const res = await fetch(tokenEndpoint, {
+ method: "POST",
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
+ body: new URLSearchParams(params).toString(),
+ });
+ const text = await res.text();
+ if (!res.ok) {
+ throw new Error(`Token request to ${tokenEndpoint} failed: ${res.status} ${text}`);
+ }
+ return JSON.parse(text);
+}
+
+function toCredentials(
+ token: { access_token: string; refresh_token?: string; expires_in?: number },
+ tokenEndpoint: string,
+ clientId: string,
+ previousRefresh?: string,
+): McpCredentials {
+ return {
+ access: token.access_token,
+ // Some servers omit refresh_token on refresh; keep the prior one.
+ refresh: token.refresh_token ?? previousRefresh ?? "",
+ expires: token.expires_in
+ ? Date.now() + token.expires_in * 1000 - TOKEN_EXPIRY_BUFFER_MS
+ : Date.now() + 3600 * 1000 - TOKEN_EXPIRY_BUFFER_MS,
+ tokenEndpoint,
+ clientId,
+ };
+}
+
+/** Build a provider for one MCP server. Register it with registerOAuthProvider(). */
+export function createMcpOAuthProvider(config: McpOAuthConfig): OAuthProviderInterface {
+ const label = config.label ?? config.server;
+
+ async function login(callbacks: OAuthLoginCallbacks): Promise<OAuthCredentials> {
+ const meta = await discover(config.url);
+ callbacks.onProgress?.(`Discovered ${meta.issuer ?? new URL(config.url).origin}`);
+
+ let clientId = config.clientId;
+ if (!clientId) {
+ if (!meta.registration_endpoint) {
+ throw new Error(
+ `${label} does not support dynamic client registration and no clientId was configured. ` +
+ `Set a pre-registered client id for this server.`,
+ );
+ }
+ callbacks.onProgress?.("Registering OAuth client…");
+ clientId = await registerClient(meta.registration_endpoint, `Prime Agent (${label})`);
+ }
+
+ const { verifier, challenge } = await generatePKCE();
+ // `state` must be independent of the PKCE verifier — the verifier is the
+ // secret used at token exchange, while `state` is echoed on the redirect URL.
+ const state = randomState();
+ const scope = config.scopes ?? meta.scopes_supported?.join(" ");
+ const cb = await startCallbackServer(label);
+ try {
+ const authParams = new URLSearchParams({
+ client_id: clientId,
+ response_type: "code",
+ redirect_uri: cb.redirectUri,
+ code_challenge: challenge,
+ code_challenge_method: "S256",
+ state,
+ });
+ if (scope) authParams.set("scope", scope);
+
+ callbacks.onAuth({
+ url: `${meta.authorization_endpoint}?${authParams.toString()}`,
+ instructions:
+ "Complete login in your browser. If the browser is on another machine, paste the final redirect URL here.",
+ });
+
+ // Race the local callback server against a manual paste (browser on
+ // another machine). The login dialog supplies onManualCodeInput; when
+ // absent we fall back to a blocking prompt after the callback resolves.
+ let result: { code: string; state: string } | null;
+ let manualCancelled = false;
+ let manualError: Error | undefined;
+ if (callbacks.onManualCodeInput) {
+ // Manual paste races the browser callback. A real paste cancels the
+ // callback waiter (we're done). On manual cancellation we still settle
+ // the waiter to avoid hanging when no redirect arrives — but only after
+ // a short grace period so an in-flight browser redirect can win first.
+ const manual = callbacks
+ .onManualCodeInput()
+ .then((input) => {
+ const parsed = parseRedirectInput(input, state); // may throw a validation error
+ cb.cancel();
+ return parsed;
+ })
+ .catch(async (err) => {
+ // A validation error on a real paste (bad state / no code) is a genuine
+ // failure to surface; a UI cancellation is not. .catch also prevents an
+ // unhandled rejection when the callback wins the race.
+ if (err instanceof Error && /state mismatch|authorization code/i.test(err.message)) {
+ manualError = err;
+ } else {
+ manualCancelled = true;
+ }
+ await new Promise((r) => setTimeout(r, 500));
+ cb.cancel();
+ return null;
+ });
+ const fromCallback = await cb.waitForCode();
+ result = fromCallback ?? (await manual);
+ if (!result && manualError) throw manualError;
+ } else {
+ result = await cb.waitForCode();
+ if (!result) {
+ const input = await callbacks.onPrompt({
+ message: "Paste the authorization code or full redirect URL:",
+ placeholder: cb.redirectUri,
+ });
+ result = parseRedirectInput(input, state);
+ }
+ }
+ if (!result) {
+ throw new Error(manualCancelled ? "Login cancelled" : "Missing authorization code");
+ }
+ if (result.state !== state) {
+ throw new Error("OAuth state mismatch");
+ }
+
+ callbacks.onProgress?.("Exchanging authorization code for tokens…");
+ const token = await exchangeToken(meta.token_endpoint, {
+ grant_type: "authorization_code",
+ code: result.code,
+ redirect_uri: cb.redirectUri,
+ client_id: clientId,
+ code_verifier: verifier,
+ });
+ return toCredentials(token, meta.token_endpoint, clientId);
+ } finally {
+ cb.server.close();
+ }
+ }
+
+ async function refreshToken(credentials: OAuthCredentials): Promise<OAuthCredentials> {
+ const creds = credentials as McpCredentials;
+ const tokenEndpoint = creds.tokenEndpoint ?? (await discover(config.url)).token_endpoint;
+ const clientId = creds.clientId ?? config.clientId;
+ if (!creds.refresh) {
+ throw new Error(`No refresh token stored for ${label}; re-run /mcp login ${config.server}`);
+ }
+ const token = await exchangeToken(tokenEndpoint, {
+ grant_type: "refresh_token",
+ refresh_token: creds.refresh,
+ ...(clientId ? { client_id: clientId } : {}),
+ });
+ return toCredentials(token, tokenEndpoint, clientId ?? "", creds.refresh);
+ }
+
+ return {
+ id: `mcp:${config.server}`,
+ name: label,
+ usesCallbackServer: true,
+ login,
+ refreshToken,
+ getApiKey: (credentials) => credentials.access,
+ };
+}
diff --git a/packages/ai/src/models.generated.ts b/packages/ai/src/models.generated.ts
index 488efa2dd1..d562b339d1 100644
--- a/packages/ai/src/models.generated.ts
+++ b/packages/ai/src/models.generated.ts
@@ -379,10 +379,10 @@ export const MODELS = {
reasoning: true,
input: ["text", "image"],
cost: {
- input: 1,
- output: 5,
- cacheRead: 0.1,
- cacheWrite: 1.25,
+ input: 1.1,
+ output: 5.5,
+ cacheRead: 0.11,
+ cacheWrite: 1.375,
},
contextWindow: 200000,
maxTokens: 64000,
@@ -396,10 +396,10 @@ export const MODELS = {
reasoning: true,
input: ["text", "image"],
cost: {
- input: 5,
- output: 25,
- cacheRead: 0.5,
- cacheWrite: 6.25,
+ input: 5.5,
+ output: 27.5,
+ cacheRead: 0.55,
+ cacheWrite: 6.875,
},
contextWindow: 200000,
maxTokens: 64000,
@@ -1630,6 +1630,23 @@ export const MODELS = {
contextWindow: 1040000,
maxTokens: 8192,
} satisfies Model<"bedrock-converse-stream">,
+ "xai.grok-4.3": {
+ id: "xai.grok-4.3",
+ name: "Grok 4.3",
+ api: "bedrock-converse-stream",
+ provider: "amazon-bedrock",
+ baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com",
+ reasoning: true,
+ input: ["text", "image"],
+ cost: {
+ input: 1.25,
+ output: 2.5,
+ cacheRead: 0.2,
+ cacheWrite: 0,
+ },
+ contextWindow: 1000000,
+ maxTokens: 131072,
+ } satisfies Model<"bedrock-converse-stream">,
"zai.glm-4.7": {
id: "zai.glm-4.7",
name: "GLM-4.7",
@@ -1683,40 +1700,6 @@ export const MODELS = {
} satisfies Model<"bedrock-converse-stream">,
},
"anthropic": {
- "claude-3-5-haiku-20241022": {
- id: "claude-3-5-haiku-20241022",
- name: "Claude Haiku 3.5",
- api: "anthropic-messages",
- provider: "anthropic",
- baseUrl: "https://api.anthropic.com",
- reasoning: false,
- input: ["text", "image"],
- cost: {
- input: 0.8,
- output: 4,
- cacheRead: 0.08,
- cacheWrite: 1,
- },
- contextWindow: 200000,
- maxTokens: 8192,
- } satisfies Model<"anthropic-messages">,
- "claude-3-5-haiku-latest": {
- id: "claude-3-5-haiku-latest",
- name: "Claude Haiku 3.5 (latest)",
- api: "anthropic-messages",
- provider: "anthropic",
- baseUrl: "https://api.anthropic.com",
- reasoning: false,
- input: ["text", "image"],
- cost: {
- input: 0.8,
- output: 4,
- cacheRead: 0.08,
- cacheWrite: 1,
- },
- contextWindow: 200000,
- maxTokens: 8192,
- } satisfies Model<"anthropic-messages">,
"claude-3-5-sonnet-20240620": {
id: "claude-3-5-sonnet-20240620",
name: "Claude Sonnet 3.5",
@@ -3879,7 +3862,7 @@ export const MODELS = {
cacheRead: 0.26,
cacheWrite: 0,
},
- contextWindow: 1048576,
+ contextWindow: 1048575,
maxTokens: 131072,
} satisfies Model<"anthropic-messages">,
"accounts/fireworks/models/gpt-oss-120b": {
@@ -4018,6 +4001,23 @@ export const MODELS = {
contextWindow: 202800,
maxTokens: 131072,
} satisfies Model<"anthropic-messages">,
+ "accounts/fireworks/routers/glm-5p2-fast": {
+ id: "accounts/fireworks/routers/glm-5p2-fast",
+ name: "GLM 5.2 Fast",
+ api: "anthropic-messages",
+ provider: "fireworks",
+ baseUrl: "https://api.fireworks.ai/inference",
+ reasoning: true,
+ input: ["text"],
+ cost: {
+ input: 2.1,
+ output: 6.6,
+ cacheRead: 0.21,
+ cacheWrite: 0,
+ },
+ contextWindow: 1048575,
+ maxTokens: 131072,
+ } satisfies Model<"anthropic-messages">,
"accounts/fireworks/routers/kimi-k2p6-fast": {
id: "accounts/fireworks/routers/kimi-k2p6-fast",
name: "Kimi K2.6 Fast",
@@ -5097,7 +5097,7 @@ export const MODELS = {
cost: {
input: 0.075,
output: 0.3,
- cacheRead: 0.037,
+ cacheRead: 0,
cacheWrite: 0,
},
contextWindow: 131072,
@@ -5771,6 +5771,24 @@ export const MODELS = {
contextWindow: 262144,
maxTokens: 262144,
} satisfies Model<"openai-completions">,
+ "openai/gpt-oss-120b": {
+ id: "openai/gpt-oss-120b",
+ name: "GPT OSS 120B",
+ api: "openai-completions",
+ provider: "huggingface",
+ baseUrl: "https://router.huggingface.co/v1",
+ compat: {"supportsDeveloperRole":false},
+ reasoning: true,
+ input: ["text"],
+ cost: {
+ input: 0.25,
+ output: 0.69,
+ cacheRead: 0,
+ cacheWrite: 0,
+ },
+ contextWindow: 131072,
+ maxTokens: 32768,
+ } satisfies Model<"openai-completions">,
"stepfun-ai/Step-3.5-Flash": {
id: "stepfun-ai/Step-3.5-Flash",
name: "Step 3.5 Flash",
@@ -8821,12 +8839,12 @@ export const MODELS = {
reasoning: true,
input: ["text", "image"],
cost: {
- input: 0.1,
- output: 0.4,
- cacheRead: 0.02,
+ input: 0.3,
+ output: 1.2,
+ cacheRead: 0.06,
cacheWrite: 0,
},
- contextWindow: 512000,
+ contextWindow: 1000000,
maxTokens: 131072,
} satisfies Model<"anthropic-messages">,
"qwen3.6-plus": {
@@ -8850,9 +8868,9 @@ export const MODELS = {
"qwen3.7-max": {
id: "qwen3.7-max",
name: "Qwen3.7 Max",
- api: "openai-completions",
+ api: "anthropic-messages",
provider: "opencode-go",
- baseUrl: "https://opencode.ai/zen/go/v1",
+ baseUrl: "https://opencode.ai/zen/go",
reasoning: true,
input: ["text"],
cost: {
@@ -8863,13 +8881,13 @@ export const MODELS = {
},
contextWindow: 1000000,
maxTokens: 65536,
- } satisfies Model<"openai-completions">,
+ } satisfies Model<"anthropic-messages">,
"qwen3.7-plus": {
id: "qwen3.7-plus",
name: "Qwen3.7 Plus",
- api: "openai-completions",
+ api: "anthropic-messages",
provider: "opencode-go",
- baseUrl: "https://opencode.ai/zen/go/v1",
+ baseUrl: "https://opencode.ai/zen/go",
reasoning: true,
input: ["text", "image"],
cost: {
@@ -8880,7 +8898,7 @@ export const MODELS = {
},
contextWindow: 1000000,
maxTokens: 65536,
- } satisfies Model<"openai-completions">,
+ } satisfies Model<"anthropic-messages">,
},
"openrouter": {
"ai21/jamba-large-1.7": {
@@ -9106,24 +9124,6 @@ export const MODELS = {
contextWindow: 1000000,
maxTokens: 128000,
} satisfies Model<"openai-completions">,
- "anthropic/claude-opus-4.6-fast": {
- id: "anthropic/claude-opus-4.6-fast",
- name: "Anthropic: Claude Opus 4.6 (Fast)",
- api: "openai-completions",
- provider: "openrouter",
- baseUrl: "https://openrouter.ai/api/v1",
- reasoning: true,
- thinkingLevelMap: {"max":"max"},
- input: ["text", "image"],
- cost: {
- input: 30,
- output: 150,
- cacheRead: 3,
- cacheWrite: 37.5,
- },
- contextWindow: 1000000,
- maxTokens: 128000,
- } satisfies Model<"openai-completions">,
"anthropic/claude-opus-4.7": {
id: "anthropic/claude-opus-4.7",
name: "Anthropic: Claude Opus 4.7",
@@ -9248,6 +9248,23 @@ export const MODELS = {
contextWindow: 1000000,
maxTokens: 128000,
} satisfies Model<"openai-completions">,
+ "anthropic/claude-sonnet-5": {
+ id: "anthropic/claude-sonnet-5",
+ name: "Anthropic: Claude Sonnet 5",
+ api: "openai-completions",
+ provider: "openrouter",
+ baseUrl: "https://openrouter.ai/api/v1",
+ reasoning: true,
+ input: ["text", "image"],
+ cost: {
+ input: 2,
+ output: 10,
+ cacheRead: 0.19999999999999998,
+ cacheWrite: 2.5,
+ },
+ contextWindow: 1000000,
+ maxTokens: 128000,
+ } satisfies Model<"openai-completions">,
"arcee-ai/trinity-large-thinking": {
id: "arcee-ai/trinity-large-thinking",
name: "Arcee AI: Trinity Large Thinking",
@@ -9548,7 +9565,7 @@ export const MODELS = {
cost: {
input: 0.2288,
output: 0.3432,
- cacheRead: 0,
+ cacheRead: 0.02288,
cacheWrite: 0,
},
contextWindow: 131072,
@@ -9582,13 +9599,13 @@ export const MODELS = {
thinkingLevelMap: {"minimal":null,"low":null,"medium":null,"high":"high","xhigh":"max"},
input: ["text"],
cost: {
- input: 0.09,
- output: 0.18,
+ input: 0.098,
+ output: 0.196,
cacheRead: 0.02,
cacheWrite: 0,
},
contextWindow: 1048576,
- maxTokens: 65536,
+ maxTokens: 4096,
} satisfies Model<"openai-completions">,
"deepseek/deepseek-v4-pro": {
id: "deepseek/deepseek-v4-pro",
@@ -10559,7 +10576,7 @@ export const MODELS = {
cacheWrite: 0,
},
contextWindow: 131072,
- maxTokens: 32768,
+ maxTokens: 100352,
} satisfies Model<"openai-completions">,
"moonshotai/kimi-k2-0905": {
id: "moonshotai/kimi-k2-0905",
@@ -10576,7 +10593,7 @@ export const MODELS = {
cacheWrite: 0,
},
contextWindow: 262144,
- maxTokens: 262144,
+ maxTokens: 100352,
} satisfies Model<"openai-completions">,
"moonshotai/kimi-k2-thinking": {
id: "moonshotai/kimi-k2-thinking",
@@ -10621,9 +10638,9 @@ export const MODELS = {
reasoning: true,
input: ["text", "image"],
cost: {
- input: 0.66,
- output: 3.41,
- cacheRead: 0.144,
+ input: 0.55,
+ output: 3.1999999999999997,
+ cacheRead: 0.11,
cacheWrite: 0,
},
contextWindow: 262144,
@@ -10723,13 +10740,13 @@ export const MODELS = {
reasoning: true,
input: ["text"],
cost: {
- input: 0.09,
- output: 0.44999999999999996,
+ input: 0.08499999999999999,
+ output: 0.39999999999999997,
cacheRead: 0,
cacheWrite: 0,
},
contextWindow: 1000000,
- maxTokens: 4096,
+ maxTokens: 16384,
} satisfies Model<"openai-completions">,
"nvidia/nemotron-3-super-120b-a12b:free": {
id: "nvidia/nemotron-3-super-120b-a12b:free",
@@ -11780,23 +11797,6 @@ export const MODELS = {
contextWindow: 200000,
maxTokens: 4096,
} satisfies Model<"openai-completions">,
- "openrouter/owl-alpha": {
- id: "openrouter/owl-alpha",
- name: "Owl Alpha",
- api: "openai-completions",
- provider: "openrouter",
- baseUrl: "https://openrouter.ai/api/v1",
- reasoning: false,
- input: ["text"],
- cost: {
- input: 0,
- output: 0,
- cacheRead: 0,
- cacheWrite: 0,
- },
- contextWindow: 1048756,
- maxTokens: 262144,
- } satisfies Model<"openai-completions">,
"poolside/laguna-m.1": {
id: "poolside/laguna-m.1",
name: "Poolside: Laguna M.1",
@@ -12554,8 +12554,8 @@ export const MODELS = {
reasoning: true,
input: ["text", "image"],
cost: {
- input: 0.28850000000000003,
- output: 3.17,
+ input: 0.28500000000000003,
+ output: 2.4,
cacheRead: 0,
cacheWrite: 0,
},
@@ -12741,13 +12741,13 @@ export const MODELS = {
reasoning: true,
input: ["text"],
cost: {
- input: 0.09,
+ input: 0.09999999999999999,
output: 0.3,
- cacheRead: 0.02,
+ cacheRead: 0,
cacheWrite: 0,
},
contextWindow: 262144,
- maxTokens: 16384,
+ maxTokens: 65536,
} satisfies Model<"openai-completions">,
"stepfun/step-3.7-flash": {
id: "stepfun/step-3.7-flash",
@@ -13064,9 +13064,9 @@ export const MODELS = {
reasoning: true,
input: ["text"],
cost: {
- input: 0.98,
- output: 3.08,
- cacheRead: 0.182,
+ input: 0.975,
+ output: 4.300000000000001,
+ cacheRead: 0,
cacheWrite: 0,
},
contextWindow: 202752,
@@ -13081,13 +13081,13 @@ export const MODELS = {
reasoning: true,
input: ["text"],
cost: {
- input: 0.95,
+ input: 0.94,
output: 3,
cacheRead: 0.18,
cacheWrite: 0,
},
contextWindow: 1048576,
- maxTokens: 32768,
+ maxTokens: 4096,
} satisfies Model<"openai-completions">,
"z-ai/glm-5v-turbo": {
id: "z-ai/glm-5v-turbo",
@@ -13166,10 +13166,10 @@ export const MODELS = {
reasoning: true,
input: ["text", "image"],
cost: {
- input: 3,
- output: 15,
- cacheRead: 0.3,
- cacheWrite: 3.75,
+ input: 2,
+ output: 10,
+ cacheRead: 0.19999999999999998,
+ cacheWrite: 2.5,
},
contextWindow: 1000000,
maxTokens: 128000,
@@ -13217,9 +13217,9 @@ export const MODELS = {
reasoning: true,
input: ["text", "image"],
cost: {
- input: 0.66,
- output: 3.41,
- cacheRead: 0.144,
+ input: 0.55,
+ output: 3.1999999999999997,
+ cacheRead: 0.11,
cacheWrite: 0,
},
contextWindow: 262144,
@@ -14462,6 +14462,23 @@ export const MODELS = {
contextWindow: 1000000,
maxTokens: 128000,
} satisfies Model<"anthropic-messages">,
+ "anthropic/claude-sonnet-5": {
+ id: "anthropic/claude-sonnet-5",
+ name: "Claude Sonnet 5",
+ api: "anthropic-messages",
+ provider: "vercel-ai-gateway",
+ baseUrl: "https://ai-gateway.vercel.sh",
+ reasoning: true,
+ input: ["text", "image"],
+ cost: {
+ input: 2,
+ output: 10,
+ cacheRead: 0.19999999999999998,
+ cacheWrite: 2.5,
+ },
+ contextWindow: 1000000,
+ maxTokens: 128000,
+ } satisfies Model<"anthropic-messages">,
"arcee-ai/trinity-large-preview": {
id: "arcee-ai/trinity-large-preview",
name: "Trinity Large Preview",
@@ -14607,13 +14624,13 @@ export const MODELS = {
reasoning: true,
input: ["text"],
cost: {
- input: 0.56,
- output: 1.68,
- cacheRead: 0.28,
+ input: 0.6,
+ output: 1.7,
+ cacheRead: 0,
cacheWrite: 0,
},
- contextWindow: 163840,
- maxTokens: 8192,
+ contextWindow: 128000,
+ maxTokens: 128000,
} satisfies Model<"anthropic-messages">,
"deepseek/deepseek-v3.1-terminus": {
id: "deepseek/deepseek-v3.1-terminus",
@@ -15559,13 +15576,13 @@ export const MODELS = {
reasoning: true,
input: ["text"],
cost: {
- input: 0.6,
- output: 2.5,
- cacheRead: 0.15,
+ input: 0.47,
+ output: 2,
+ cacheRead: 0.14100000000000001,
cacheWrite: 0,
},
- contextWindow: 262114,
- maxTokens: 262114,
+ contextWindow: 216144,
+ maxTokens: 216144,
} satisfies Model<"anthropic-messages">,
"moonshotai/kimi-k2.5": {
id: "moonshotai/kimi-k2.5",
@@ -16251,13 +16268,13 @@ export const MODELS = {
reasoning: true,
input: ["text"],
cost: {
- input: 0.35,
- output: 0.75,
- cacheRead: 0.25,
+ input: 0.09999999999999999,
+ output: 0.5,
+ cacheRead: 0,
cacheWrite: 0,
},
contextWindow: 131072,
- maxTokens: 131000,
+ maxTokens: 131072,
} satisfies Model<"anthropic-messages">,
"openai/gpt-oss-20b": {
id: "openai/gpt-oss-20b",
@@ -16686,7 +16703,7 @@ export const MODELS = {
} satisfies Model<"anthropic-messages">,
"zai/glm-4.5": {
id: "zai/glm-4.5",
- name: "GLM-4.5",
+ name: "GLM 4.5",
api: "anthropic-messages",
provider: "vercel-ai-gateway",
baseUrl: "https://ai-gateway.vercel.sh",
@@ -16795,13 +16812,13 @@ export const MODELS = {
reasoning: true,
input: ["text"],
cost: {
- input: 2.25,
- output: 2.75,
- cacheRead: 2.25,
+ input: 0.6,
+ output: 2.2,
+ cacheRead: 0.12,
cacheWrite: 0,
},
- contextWindow: 131000,
- maxTokens: 40000,
+ contextWindow: 200000,
+ maxTokens: 120000,
} satisfies Model<"anthropic-messages">,
"zai/glm-4.7-flash": {
id: "zai/glm-4.7-flash",
@@ -16846,8 +16863,8 @@ export const MODELS = {
reasoning: true,
input: ["text"],
cost: {
- input: 1,
- output: 3.1999999999999997,
+ input: 0.95,
+ output: 3.15,
cacheRead: 0.19999999999999998,
cacheWrite: 0,
},
@@ -16880,13 +16897,13 @@ export const MODELS = {
reasoning: true,
input: ["text"],
cost: {
- input: 1.4,
- output: 4.4,
+ input: 1.3,
+ output: 4.300000000000001,
cacheRead: 0.26,
cacheWrite: 0,
},
- contextWindow: 202800,
- maxTokens: 64000,
+ contextWindow: 202000,
+ maxTokens: 202000,
} satisfies Model<"anthropic-messages">,
"zai/glm-5.2": {
id: "zai/glm-5.2",
@@ -17037,9 +17054,9 @@ export const MODELS = {
reasoning: true,
input: ["text"],
cost: {
- input: 0.1,
- output: 0.3,
- cacheRead: 0.01,
+ input: 0.14,
+ output: 0.28,
+ cacheRead: 0.0028,
cacheWrite: 0,
},
contextWindow: 262144,
@@ -17054,9 +17071,9 @@ export const MODELS = {
reasoning: true,
input: ["text", "image"],
cost: {
- input: 0.4,
- output: 2,
- cacheRead: 0.08,
+ input: 0.14,
+ output: 0.28,
+ cacheRead: 0.0028,
cacheWrite: 0,
},
contextWindow: 262144,
@@ -17071,9 +17088,9 @@ export const MODELS = {
reasoning: true,
input: ["text"],
cost: {
- input: 1,
- output: 3,
- cacheRead: 0.2,
+ input: 0.435,
+ output: 0.87,
+ cacheRead: 0.0036,
cacheWrite: 0,
},
contextWindow: 1048576,
@@ -17088,9 +17105,9 @@ export const MODELS = {
reasoning: true,
input: ["text", "image"],
cost: {
- input: 0.4,
- output: 2,
- cacheRead: 0.08,
+ input: 0.14,
+ output: 0.28,
+ cacheRead: 0.0028,
cacheWrite: 0,
},
contextWindow: 1048576,
@@ -17105,9 +17122,9 @@ export const MODELS = {
reasoning: true,
input: ["text"],
cost: {
- input: 1,
- output: 3,
- cacheRead: 0.2,
+ input: 0.435,
+ output: 0.87,
+ cacheRead: 0.0036,
cacheWrite: 0,
},
contextWindow: 1048576,
@@ -17141,9 +17158,9 @@ export const MODELS = {
reasoning: true,
input: ["text"],
cost: {
- input: 0.1,
- output: 0.3,
- cacheRead: 0.01,
+ input: 0.14,
+ output: 0.28,
+ cacheRead: 0.0028,
cacheWrite: 0,
},
contextWindow: 262144,
@@ -17158,9 +17175,9 @@ export const MODELS = {
reasoning: true,
input: ["text", "image"],
cost: {
- input: 0.4,
- output: 2,
- cacheRead: 0.08,
+ input: 0.14,
+ output: 0.28,
+ cacheRead: 0.0028,
cacheWrite: 0,
},
contextWindow: 262144,
@@ -17175,9 +17192,9 @@ export const MODELS = {
reasoning: true,
input: ["text"],
cost: {
- input: 1,
- output: 3,
- cacheRead: 0.2,
+ input: 0.435,
+ output: 0.87,
+ cacheRead: 0.0036,
cacheWrite: 0,
},
contextWindow: 1048576,
@@ -17192,9 +17209,9 @@ export const MODELS = {
reasoning: true,
input: ["text", "image"],
cost: {
- input: 0.4,
- output: 2,
- cacheRead: 0.08,
+ input: 0.14,
+ output: 0.28,
+ cacheRead: 0.0028,
cacheWrite: 0,
},
contextWindow: 1048576,
@@ -17209,9 +17226,9 @@ export const MODELS = {
reasoning: true,
input: ["text"],
cost: {
- input: 1,
- output: 3,
- cacheRead: 0.2,
+ input: 0.435,
+ output: 0.87,
+ cacheRead: 0.0036,
cacheWrite: 0,
},
contextWindow: 1048576,
@@ -17245,9 +17262,9 @@ export const MODELS = {
reasoning: true,
input: ["text"],
cost: {
- input: 0.1,
- output: 0.3,
- cacheRead: 0.01,
+ input: 0.14,
+ output: 0.28,
+ cacheRead: 0.0028,
cacheWrite: 0,
},
contextWindow: 262144,
@@ -17262,9 +17279,9 @@ export const MODELS = {
reasoning: true,
input: ["text", "image"],
cost: {
- input: 0.4,
- output: 2,
- cacheRead: 0.08,
+ input: 0.14,
+ output: 0.28,
+ cacheRead: 0.0028,
cacheWrite: 0,
},
contextWindow: 262144,
@@ -17279,9 +17296,9 @@ export const MODELS = {
reasoning: true,
input: ["text"],
cost: {
- input: 1,
- output: 3,
- cacheRead: 0.2,
+ input: 0.435,
+ output: 0.87,
+ cacheRead: 0.0036,
cacheWrite: 0,
},
contextWindow: 1048576,
@@ -17296,9 +17313,9 @@ export const MODELS = {
reasoning: true,
input: ["text", "image"],
cost: {
- input: 0.4,
- output: 2,
- cacheRead: 0.08,
+ input: 0.14,
+ output: 0.28,
+ cacheRead: 0.0028,
cacheWrite: 0,
},
contextWindow: 1048576,
@@ -17313,9 +17330,9 @@ export const MODELS = {
reasoning: true,
input: ["text"],
cost: {
- input: 1,
- output: 3,
- cacheRead: 0.2,
+ input: 0.435,
+ output: 0.87,
+ cacheRead: 0.0036,
cacheWrite: 0,
},
contextWindow: 1048576,
@@ -17349,9 +17366,9 @@ export const MODELS = {
reasoning: true,
input: ["text"],
cost: {
- input: 0.1,
- output: 0.3,
- cacheRead: 0.01,
+ input: 0.14,
+ output: 0.28,
+ cacheRead: 0.0028,
cacheWrite: 0,
},
contextWindow: 262144,
@@ -17366,9 +17383,9 @@ export const MODELS = {
reasoning: true,
input: ["text", "image"],
cost: {
- input: 0.4,
- output: 2,
- cacheRead: 0.08,
+ input: 0.14,
+ output: 0.28,
+ cacheRead: 0.0028,
cacheWrite: 0,
},
contextWindow: 262144,
@@ -17383,9 +17400,9 @@ export const MODELS = {
reasoning: true,
input: ["text"],
cost: {
- input: 1,
- output: 3,
- cacheRead: 0.2,
+ input: 0.435,
+ output: 0.87,
+ cacheRead: 0.0036,
cacheWrite: 0,
},
contextWindow: 1048576,
@@ -17400,9 +17417,9 @@ export const MODELS = {
reasoning: true,
input: ["text", "image"],
cost: {
- input: 0.4,
- output: 2,
- cacheRead: 0.08,
+ input: 0.14,
+ output: 0.28,
+ cacheRead: 0.0028,
cacheWrite: 0,
},
contextWindow: 1048576,
@@ -17417,9 +17434,9 @@ export const MODELS = {
reasoning: true,
input: ["text"],
cost: {
- input: 1,
- output: 3,
- cacheRead: 0.2,
+ input: 0.435,
+ output: 0.87,
+ cacheRead: 0.0036,
cacheWrite: 0,
},
contextWindow: 1048576,
diff --git a/packages/ai/test/mcp-oauth.test.ts b/packages/ai/test/mcp-oauth.test.ts
new file mode 100644
index 0000000000..298915a540
--- /dev/null
+++ b/packages/ai/test/mcp-oauth.test.ts
@@ -0,0 +1,162 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { createMcpOAuthProvider } from "../src/mcp/oauth.js";
+
+function jsonResponse(body: unknown, status = 200): Response {
+ return new Response(JSON.stringify(body), { status, headers: { "Content-Type": "application/json" } });
+}
+
+function urlOf(input: unknown): string {
+ if (typeof input === "string") return input;
+ if (input instanceof URL) return input.toString();
+ if (input instanceof Request) return input.url;
+ throw new Error(`Unsupported fetch input: ${String(input)}`);
+}
+
+const META = {
+ issuer: "https://srv.test",
+ authorization_endpoint: "https://srv.test/authorize",
+ token_endpoint: "https://srv.test/token",
+ registration_endpoint: "https://srv.test/register",
+ scopes_supported: ["read", "write"],
+};
+
+describe.sequential("MCP OAuth provider", () => {
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ it("has a namespaced id and label", () => {
+ const provider = createMcpOAuthProvider({ server: "linear", label: "Linear", url: "https://srv.test/mcp" });
+ expect(provider.id).toBe("mcp:linear");
+ expect(provider.name).toBe("Linear");
+ expect(provider.usesCallbackServer).toBe(true);
+ });
+
+ it("discovers, registers a client, and exchanges the code for tokens", async () => {
+ let authUrl = "";
+ const fetchMock = vi.fn(async (input: unknown, init?: RequestInit): Promise<Response> => {
+ const url = urlOf(input);
+ if (url.endsWith("/.well-known/oauth-authorization-server")) return jsonResponse(META);
+ if (url === META.registration_endpoint) return jsonResponse({ client_id: "client-xyz" });
+ if (url === META.token_endpoint) {
+ const params = new URLSearchParams(String(init?.body));
+ expect(params.get("grant_type")).toBe("authorization_code");
+ expect(params.get("client_id")).toBe("client-xyz");
+ expect(params.get("code")).toBe("the-code");
+ expect(params.get("code_verifier")).toBeTruthy();
+ return jsonResponse({ access_token: "access-1", refresh_token: "refresh-1", expires_in: 3600 });
+ }
+ throw new Error(`unexpected fetch: ${url}`);
+ });
+ vi.stubGlobal("fetch", fetchMock);
+
+ const provider = createMcpOAuthProvider({ server: "demo", url: "https://srv.test/mcp" });
+ const creds = await provider.login({
+ onAuth: (info) => {
+ authUrl = info.url;
+ },
+ onPrompt: async () => "",
+ // Headless: supply the redirect URL via the manual-input path, which
+ // races (and wins against) the local callback server.
+ onManualCodeInput: async () => {
+ const state = new URL(authUrl).searchParams.get("state") ?? "";
+ return `${REDIRECT}?code=the-code&state=${state}`;
+ },
+ });
+
+ expect(creds.access).toBe("access-1");
+ expect(creds.refresh).toBe("refresh-1");
+ expect(creds.expires).toBeGreaterThan(Date.now());
+ // auth URL carries PKCE challenge + registered client id
+ const authParams = new URL(authUrl).searchParams;
+ expect(authParams.get("client_id")).toBe("client-xyz");
+ expect(authParams.get("code_challenge")).toBeTruthy();
+ expect(authParams.get("scope")).toBe("read write");
+ });
+
+ it("falls back to the next port when the base callback port is in use", async () => {
+ const http = await import("node:http");
+ // Occupy the base callback port. If something already holds it (e.g. a stray
+ // local daemon), that satisfies the precondition too — bind best-effort.
+ const blocker = http.createServer();
+ const blockerBound = await new Promise<boolean>((resolve) => {
+ blocker.once("error", () => resolve(false));
+ blocker.listen(53700, "127.0.0.1", () => resolve(true));
+ });
+ try {
+ let authUrl = "";
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (input: unknown): Promise<Response> => {
+ const url = urlOf(input);
+ if (url.endsWith("/.well-known/oauth-authorization-server")) return jsonResponse(META);
+ if (url === META.registration_endpoint) return jsonResponse({ client_id: "c" });
+ if (url === META.token_endpoint) return jsonResponse({ access_token: "a", expires_in: 60 });
+ throw new Error(`unexpected fetch: ${url}`);
+ }),
+ );
+ const provider = createMcpOAuthProvider({ server: "demo", url: "https://srv.test/mcp" });
+ const creds = await provider.login({
+ onAuth: (info) => {
+ authUrl = info.url;
+ },
+ onPrompt: async () => "",
+ onManualCodeInput: async () => {
+ const p = new URL(authUrl).searchParams;
+ return `${p.get("redirect_uri")}?code=x&state=${p.get("state")}`;
+ },
+ });
+ expect(creds.access).toBe("a");
+ // Did NOT use the blocked base port.
+ const redirect = new URL(authUrl).searchParams.get("redirect_uri") ?? "";
+ expect(redirect).not.toContain(":53700/");
+ expect(redirect).toContain(":5370");
+ } finally {
+ if (blockerBound) await new Promise<void>((resolve) => blocker.close(() => resolve()));
+ }
+ });
+
+ it("refreshes tokens, keeping the prior refresh token when omitted", async () => {
+ const fetchMock = vi.fn(async (input: unknown, init?: RequestInit): Promise<Response> => {
+ const url = urlOf(input);
+ if (url === META.token_endpoint) {
+ const params = new URLSearchParams(String(init?.body));
+ expect(params.get("grant_type")).toBe("refresh_token");
+ expect(params.get("refresh_token")).toBe("old-refresh");
+ return jsonResponse({ access_token: "access-2", expires_in: 1800 });
+ }
+ throw new Error(`unexpected fetch: ${url}`);
+ });
+ vi.stubGlobal("fetch", fetchMock);
+
+ const provider = createMcpOAuthProvider({ server: "demo", url: "https://srv.test/mcp" });
+ const refreshed = await provider.refreshToken({
+ access: "access-1",
+ refresh: "old-refresh",
+ expires: Date.now() - 1000,
+ tokenEndpoint: META.token_endpoint,
+ clientId: "client-xyz",
+ } as never);
+
+ expect(refreshed.access).toBe("access-2");
+ expect(refreshed.refresh).toBe("old-refresh");
+ });
+
+ it("fails clearly when DCR is unavailable and no clientId is set", async () => {
+ const noReg = { ...META, registration_endpoint: undefined };
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (input: unknown) => {
+ const url = urlOf(input);
+ if (url.endsWith("/.well-known/oauth-authorization-server")) return jsonResponse(noReg);
+ throw new Error(`unexpected fetch: ${url}`);
+ }),
+ );
+ const provider = createMcpOAuthProvider({ server: "slackish", url: "https://srv.test/mcp" });
+ await expect(provider.login({ onAuth: () => {}, onPrompt: async () => "" })).rejects.toThrow(
+ "dynamic client registration",
+ );
+ });
+});
+
+const REDIRECT = `http://localhost:${process.env.PI_MCP_OAUTH_CALLBACK_PORT || 53700}/callback`;
diff --git a/packages/coding-agent/README.md b/packages/coding-agent/README.md
index 42f978011b..a84187acad 100644
--- a/packages/coding-agent/README.md
+++ b/packages/coding-agent/README.md
@@ -32,6 +32,7 @@ This workspace still keeps an inherited source package name internally. The dist
- [Customization](#customization)
- [Prompt Templates](#prompt-templates)
- [Skills](#skills)
+ - [MCP Integrations](#mcp-integrations)
- [Extensions](#extensions)
- [Themes](#themes)
- [Prime Agent Packages](#prime-agent-packages)
@@ -305,6 +306,53 @@ Place in `~/.prime/agent/skills/`, `~/.agents/skills/`, `.prime/agent/skills/`,
Prime Agent ships with a built-in `websearch` skill (Google search via the [Serper](https://serper.dev) API). It loads by default; run `/login` and choose "Serper (web search)" to add your key, disable it with `bundledSkills.websearch: false`, or override it with your own `websearch` skill in any location above. See [docs/skills.md#built-in-skills](docs/skills.md#built-in-skills).
+### MCP Integrations
+
+Connect external services (Linear, Notion, …) over the [Model Context Protocol](https://modelcontextprotocol.io). Consistent with the single-tool design, MCP is **not** exposed as new agent tools — each integration is a Python skill package the model imports and calls from the kernel:
+
+```python
+import linear
+issues = await linear.list_issues(team="Engineering") # tools auto-discovered from the server
+help(linear.list_issues) # description + argument schema
+```
+
+Built-in integrations for Linear and Notion ship disabled. **Logging in enables them**: open `/login`, switch to the **Services** tab, pick the integration, and complete OAuth in the browser. The integration's skill then becomes visible and is auto-imported into the kernel. `/mcp` offers the same from the command line:
+
+```
+/mcp list integrations and connection status
+/mcp login <name> connect via OAuth (browser)
+/mcp logout <name> disconnect
+```
+
+Credentials are stored once in `~/.prime/agent/auth.json` (under `mcp:<name>`); the kernel reads them directly and the host refreshes expired tokens. Enablement is derived from whether valid credentials exist, so there is no separate on/off switch.
+
+**Add your own server.** Declare it under `mcpServers` in settings, then ship a tiny Python skill package that subclasses `McpIntegration`:
+
+```jsonc
+// ~/.prime/settings.json
+{
+ "mcpServers": {
+ "acme": { "type": "http", "url": "https://mcp.acme.com/mcp", "oauth": true }
+ }
+}
+```
+
+```python
+# ~/.prime/agent/skills/acme/src/acme/__init__.py
+from rlm import McpIntegration
+
+class Acme(McpIntegration):
+ server = "acme"
+ url = "https://mcp.acme.com/mcp"
+
+acme = Acme()
+
+def __getattr__(name): # so `import acme; await acme.<tool>(...)` works
+ return getattr(acme, name)
+```
+
+The base class connects with the official `mcp` SDK, injects the bearer token from `auth.json`, and binds the server's tools as async methods. Use `await acme.call_tool("name", {...})` for tools whose names aren't valid Python identifiers, or a static `bearerTokenEnvVar` instead of OAuth.
+
### Extensions
<p align="center"><img src="docs/images/doom-extension.png" alt="Doom Extension" width="600"></p>
diff --git a/packages/coding-agent/skills/linear/SKILL.md b/packages/coding-agent/skills/linear/SKILL.md
new file mode 100644
index 0000000000..a5247546c3
--- /dev/null
+++ b/packages/coding-agent/skills/linear/SKILL.md
@@ -0,0 +1,45 @@
+---
+name: linear
+description: Read and write Linear issues, projects, cycles, comments, and more via Linear's official MCP server. Tools are auto-discovered from the server at runtime.
+---
+
+# Linear
+
+Talk to Linear through its official hosted MCP server from the IPython kernel.
+
+## Setup
+
+Connect via `/login` → **Services** tab → **Linear** (OAuth in the browser).
+`/mcp login linear` does the same. Once connected, this skill is enabled
+automatically. If a call raises `NotEnabled`, the user isn't logged in — walk
+them through `/login`; don't ask them to set environment variables.
+
+## Usage
+
+The tool set is defined by the server, not by this skill, so **discover before
+you call** — don't assume tool names or argument names:
+
+```python
+import linear
+
+# 1. Discover available tools
+for tool in await linear.list_tools():
+ print(tool["name"], "-", tool["description"])
+
+# 2. Inspect a specific tool's arguments (rendered from its JSON Schema)
+help(linear.list_issues)
+
+# 3. Call it; keyword args must match the tool's input schema
+result = await linear.list_issues(team="Engineering")
+print(result)
+```
+
+Notes:
+- Every tool is an `async` method — always `await`.
+- Results are already-parsed Python (a `dict` for structured output, otherwise a
+ string). No need to `json.loads` them.
+- For tools whose names aren't valid Python identifiers, use the escape hatch:
+ `await linear.call_tool("tool-name", {"arg": "value"})`.
+- Run `list_tools()` before relying on `help()` or assuming a tool exists — it
+ populates the schemas `help()` shows, and the server is the source of truth
+ for tool names and arguments.
diff --git a/packages/coding-agent/skills/linear/pyproject.toml b/packages/coding-agent/skills/linear/pyproject.toml
new file mode 100644
index 0000000000..95c0ad08e3
--- /dev/null
+++ b/packages/coding-agent/skills/linear/pyproject.toml
@@ -0,0 +1,13 @@
+[project]
+name = "prime-agent-skill-linear"
+version = "0.1.0"
+description = "Linear integration skill for Prime Agent (Linear's official MCP server)."
+requires-python = ">=3.10"
+dependencies = ["mcp", "httpx", "prime-agent-runtime"]
+
+[build-system]
+requires = ["hatchling"]
+build-backend = "hatchling.build"
+
+[tool.hatch.build.targets.wheel]
+packages = ["src/linear"]
diff --git a/packages/coding-agent/skills/linear/src/linear/__init__.py b/packages/coding-agent/skills/linear/src/linear/__init__.py
new file mode 100644
index 0000000000..9cfce0a1d5
--- /dev/null
+++ b/packages/coding-agent/skills/linear/src/linear/__init__.py
@@ -0,0 +1,35 @@
+"""Linear integration: tools auto-discovered from Linear's official MCP server.
+
+Usage in the kernel:
+
+ import linear
+ issues = await linear.list_issues(team="Engineering")
+"""
+
+from __future__ import annotations
+
+from rlm import McpIntegration
+
+__all__ = ["Linear", "linear"]
+
+
+class Linear(McpIntegration):
+ server = "linear"
+ url = "https://mcp.linear.app/mcp"
+
+
+linear = Linear()
+
+
+# Names the kernel bootstrap probes to decide if a module is a callable skill.
+# Don't forward them, or `getattr(module, "run")` returns an MCP tool stub and the
+# module gets wrapped as callable, breaking `await linear.<tool>()` dispatch.
+_RESERVED = {"run", "__wrapped__", "__call__"}
+
+
+def __getattr__(name: str):
+ # Forward bare module-level access (e.g. linear.list_issues) to the instance,
+ # so `import linear; await linear.list_issues(...)` works without `.linear`.
+ if name.startswith("_") or name in _RESERVED:
+ raise AttributeError(name)
+ return getattr(linear, name)
diff --git a/packages/coding-agent/skills/notion/SKILL.md b/packages/coding-agent/skills/notion/SKILL.md
new file mode 100644
index 0000000000..2978376f28
--- /dev/null
+++ b/packages/coding-agent/skills/notion/SKILL.md
@@ -0,0 +1,49 @@
+---
+name: notion
+description: Search Notion and read/create/update pages and databases via Notion's official hosted MCP server. Tools are auto-discovered from the server at runtime.
+---
+
+# Notion
+
+Talk to Notion through its official hosted MCP server from the IPython kernel.
+
+## Setup
+
+Connect via `/login` → **Services** tab → **Notion** (OAuth in the browser).
+`/mcp login notion` does the same. Once connected, this skill is enabled
+automatically. If a call raises `NotEnabled`, the user isn't logged in — walk
+them through `/login`; don't ask them to set environment variables.
+
+## Usage
+
+The tool set is defined by the server, not by this skill, so **discover before
+you call** — don't assume tool names or argument names:
+
+Notion's tools are named with hyphens (e.g. `notion-search`, `notion-fetch`),
+which are **not** valid Python identifiers — so call them via `call_tool`:
+
+```python
+import notion
+
+# 1. Discover available tools (returns names + schemas)
+for tool in await notion.list_tools():
+ print(tool["name"], "-", tool["description"])
+
+# 2. Call by exact name; the second arg matches the tool's input schema
+result = await notion.call_tool("notion-search", {"query": "roadmap"})
+print(result)
+```
+
+Tools whose names *are* valid identifiers can also be called as
+`await notion.<tool>(**args)`, and `help(notion.<tool>)` shows their schema once
+`list_tools()` has run.
+
+Notes:
+- Every call is `async` — always `await`.
+- Results are already-parsed Python (a `dict` for structured output, otherwise a
+ string). No need to `json.loads` them.
+- Run `list_tools()` before relying on `help()` or assuming a tool exists — the
+ server's schema is the source of truth for names and arguments.
+- The kernel import name is `notion`. On a custom `PRIME_AGENT_KERNEL_PYTHON` that
+ already has the unrelated PyPI `notion` client installed, `import notion` may
+ resolve to that instead; use the default managed kernel venv to avoid the clash.
diff --git a/packages/coding-agent/skills/notion/pyproject.toml b/packages/coding-agent/skills/notion/pyproject.toml
new file mode 100644
index 0000000000..b399d3ae35
--- /dev/null
+++ b/packages/coding-agent/skills/notion/pyproject.toml
@@ -0,0 +1,13 @@
+[project]
+name = "prime-agent-skill-notion"
+version = "0.1.0"
+description = "Notion integration skill for Prime Agent (Notion's official hosted MCP server)."
+requires-python = ">=3.10"
+dependencies = ["mcp", "httpx", "prime-agent-runtime"]
+
+[build-system]
+requires = ["hatchling"]
+build-backend = "hatchling.build"
+
+[tool.hatch.build.targets.wheel]
+packages = ["src/notion"]
diff --git a/packages/coding-agent/skills/notion/src/notion/__init__.py b/packages/coding-agent/skills/notion/src/notion/__init__.py
new file mode 100644
index 0000000000..773f098c5a
--- /dev/null
+++ b/packages/coding-agent/skills/notion/src/notion/__init__.py
@@ -0,0 +1,31 @@
+"""Notion integration: tools auto-discovered from Notion's official MCP server.
+
+Usage in the kernel:
+
+ import notion
+ results = await notion.search(query="roadmap")
+"""
+
+from __future__ import annotations
+
+from rlm import McpIntegration
+
+__all__ = ["Notion", "notion"]
+
+
+class Notion(McpIntegration):
+ server = "notion"
+ url = "https://mcp.notion.com/mcp"
+
+
+notion = Notion()
+
+# Don't forward names the kernel bootstrap probes (e.g. `run`) or it wraps the
+# module as a callable skill and breaks `await notion.<tool>()` dispatch.
+_RESERVED = {"run", "__wrapped__", "__call__"}
+
+
+def __getattr__(name: str):
+ if name.startswith("_") or name in _RESERVED:
+ raise AttributeError(name)
+ return getattr(notion, name)
diff --git a/packages/coding-agent/src/core/agent-session-services.ts b/packages/coding-agent/src/core/agent-session-services.ts
index 16af3b0fc5..294206219a 100644
--- a/packages/coding-agent/src/core/agent-session-services.ts
+++ b/packages/coding-agent/src/core/agent-session-services.ts
@@ -6,6 +6,7 @@ import { installAgentTraceUpload } from "./agent-traces.js";
import { AuthStorage } from "./auth-storage.js";
import type { AgentRlmHeartbeatController } from "./cron-jobs.js";
import type { SessionStartEvent, ToolDefinition } from "./extensions/index.js";
+import { McpManager } from "./mcp/mcp-manager.js";
import { ModelRegistry } from "./model-registry.js";
import { DefaultResourceLoader, type DefaultResourceLoaderOptions, type ResourceLoader } from "./resource-loader.js";
import type { SubagentRuntimeHost } from "./rlm-runtime.js";
@@ -86,6 +87,7 @@ export interface AgentSessionServices {
settingsManager: SettingsManager;
modelRegistry: ModelRegistry;
resourceLoader: ResourceLoader;
+ mcpManager: McpManager;
diagnostics: AgentSessionRuntimeDiagnostic[];
}
@@ -150,11 +152,22 @@ export async function createAgentSessionServices(
const authStorage = options.authStorage ?? AuthStorage.create(join(agentDir, "auth.json"));
const settingsManager = options.settingsManager ?? SettingsManager.create(cwd, agentDir);
const modelRegistry = options.modelRegistry ?? ModelRegistry.create(authStorage, join(agentDir, "models.json"));
+
+ // MCP integrations: registers OAuth providers and gates the built-in
+ // integration skills by whether the user is logged in (enable-by-login).
+ const mcpManager = new McpManager({
+ authStorage,
+ getUserServers: () => settingsManager.getMcpServers(),
+ });
+ // refresh() resets the OAuth registry to built-ins; re-add user MCP providers too.
+ modelRegistry.setOnOAuthProvidersReset(() => mcpManager.registerUserProviders());
+
const resourceLoader = new DefaultResourceLoader({
...(options.resourceLoaderOptions ?? {}),
cwd,
agentDir,
settingsManager,
+ extraBuiltinSkillOverrides: () => mcpManager.getDisabledBuiltinSkillOverrides(),
});
await resourceLoader.reload();
@@ -181,6 +194,7 @@ export async function createAgentSessionServices(
settingsManager,
modelRegistry,
resourceLoader,
+ mcpManager,
diagnostics,
};
}
@@ -206,6 +220,7 @@ export async function createAgentSessionFromServices(
settingsManager: options.services.settingsManager,
modelRegistry: options.services.modelRegistry,
resourceLoader: options.services.resourceLoader,
+ mcpManager: options.services.mcpManager,
sessionManager: options.sessionManager,
model: options.model,
thinkingLevel: options.thinkingLevel,
diff --git a/packages/coding-agent/src/core/agent-session.ts b/packages/coding-agent/src/core/agent-session.ts
index fc3c0e24d5..729a57d8ea 100644
--- a/packages/coding-agent/src/core/agent-session.ts
+++ b/packages/coding-agent/src/core/agent-session.ts
@@ -116,6 +116,7 @@ import {
} from "./goals.js";
import type { HostRequestHandlers } from "./kernel/index.js";
import { type RestoreResult, snapshotPathIn } from "./kernel/state-snapshot.js";
+import type { McpManager } from "./mcp/mcp-manager.js";
import type { BashExecutionMessage, CustomMessage } from "./messages.js";
import type { ModelRegistry } from "./model-registry.js";
import { expandPromptTemplate, type PromptTemplate } from "./prompt-templates.js";
@@ -316,6 +317,11 @@ export interface AgentSessionConfig {
* When omitted, rlm_heartbeat.* host requests are unavailable.
*/
rlmHeartbeatController?: AgentRlmHeartbeatController;
+ /**
+ * Optional MCP integration manager. When present, its mcp.* host requests
+ * (refresh, begin_login) are exposed to the kernel.
+ */
+ mcpManager?: McpManager;
/**
* Override base tools (useful for custom runtimes).
*
@@ -722,6 +728,7 @@ export class AgentSession {
private _allowedToolNames?: Set<string>;
private _includeGoals: boolean;
private _rlmHeartbeatController?: AgentRlmHeartbeatController;
+ private _mcpManager?: McpManager;
private _baseToolsOverride?: Record<string, AgentTool>;
private _sessionStartEvent: SessionStartEvent;
private _extensionUIContext?: ExtensionUIContext;
@@ -773,6 +780,7 @@ export class AgentSession {
this._allowedToolNames = config.allowedToolNames ? new Set(config.allowedToolNames) : undefined;
this._includeGoals = config.includeGoals ?? true;
this._rlmHeartbeatController = config.rlmHeartbeatController;
+ this._mcpManager = config.mcpManager;
this._baseToolsOverride = config.baseToolsOverride;
this._sessionStartEvent = config.sessionStartEvent ?? { type: "session_start", reason: "startup" };
this._rlmDepth = config.rlmDepth ?? parseDepth(process.env.RLM_DEPTH, 0, "RLM_DEPTH");
@@ -3775,6 +3783,9 @@ export class AgentSession {
handlers[type] = async (payload) => this.handleRlmHeartbeatHostRequest(type, payload);
}
}
+ if (this._mcpManager) {
+ Object.assign(handlers, this._mcpManager.hostHandlers());
+ }
return handlers;
}
@@ -3782,7 +3793,12 @@ export class AgentSession {
const previousFlagValues = this._extensionRunner.getFlagValues();
await emitSessionShutdownEvent(this._extensionRunner, { type: "session_shutdown", reason: "reload" });
await this.settingsManager.reload();
+ // Re-read auth.json: a login saved by the client process (daemon mode) must be
+ // visible here so MCP skill gating sees the new credentials.
+ this._modelRegistry.authStorage.reload();
resetApiProviders();
+ // Re-read mcpServers and re-register user MCP providers from the reloaded settings.
+ this._mcpManager?.refresh();
await this._resourceLoader.reload();
this._buildRuntime({
activeToolNames: this.getActiveToolNames(),
diff --git a/packages/coding-agent/src/core/mcp/mcp-manager.ts b/packages/coding-agent/src/core/mcp/mcp-manager.ts
new file mode 100644
index 0000000000..58eafb6632
--- /dev/null
+++ b/packages/coding-agent/src/core/mcp/mcp-manager.ts
@@ -0,0 +1,205 @@
+// Host side of MCP integrations. The protocol itself runs Python-side in the kernel; the host
+// only registers OAuth providers, gates integration skills by auth, and serves mcp.* host-requests.
+
+import {
+ BUILTIN_MCP_CATALOG,
+ createMcpOAuthProvider,
+ getCatalogEntry,
+ registerBuiltinMcpOAuthProviders,
+} from "@earendil-works/pi-ai/mcp";
+import { registerOAuthProvider, unregisterOAuthProvider } from "@earendil-works/pi-ai/oauth";
+import type { AuthStorage } from "../auth-storage.js";
+import type { McpServerConfig } from "../settings-manager.js";
+
+export interface McpManagerOptions {
+ authStorage: AuthStorage;
+ /** Reads the current Settings.mcpServers (name → config). Re-read on refresh(). */
+ getUserServers?: () => Record<string, McpServerConfig> | undefined;
+ /** Start an interactive host-side login for a server. Provided by the UI mode. */
+ beginLogin?: (server: string) => Promise<void>;
+}
+
+/** A resolved integration: a catalog/user entry plus its provider id. */
+interface ResolvedIntegration {
+ server: string;
+ label: string;
+ url: string;
+ usesOAuth: boolean;
+ bearerTokenEnvVar?: string;
+ enabled?: boolean;
+ /** Extra static HTTP headers from the user config. */
+ headers?: Record<string, string>;
+ /** True when this came from Settings.mcpServers (may override a catalog name). */
+ userDeclared?: boolean;
+}
+
+export class McpManager {
+ private readonly authStorage: AuthStorage;
+ private readonly getUserServers: () => Record<string, McpServerConfig> | undefined;
+ private readonly beginLogin?: (server: string) => Promise<void>;
+ private integrations = new Map<string, ResolvedIntegration>();
+ /** Provider ids we registered for user servers, so refresh can drop removed ones. */
+ private registeredUserProviderIds = new Set<string>();
+
+ constructor(options: McpManagerOptions) {
+ this.authStorage = options.authStorage;
+ this.getUserServers = options.getUserServers ?? (() => undefined);
+ this.beginLogin = options.beginLogin;
+ this.resolveIntegrations();
+ this.registerProviders();
+ }
+
+ /** Re-read settings and re-register providers; call after a session reload. */
+ refresh(): void {
+ this.resolveIntegrations();
+ this.registerProviders();
+ }
+
+ private providerId(server: string): string {
+ return `mcp:${server}`;
+ }
+
+ private resolveIntegrations(): void {
+ const integrations = new Map<string, ResolvedIntegration>();
+ for (const entry of BUILTIN_MCP_CATALOG) {
+ integrations.set(entry.server, {
+ server: entry.server,
+ label: entry.label,
+ url: entry.url,
+ usesOAuth: entry.oauth?.kind === "oauth",
+ });
+ }
+ for (const [server, config] of Object.entries(this.getUserServers() ?? {})) {
+ if (config.type !== "http") continue; // stdio servers self-manage in Python
+ integrations.set(server, {
+ server,
+ label: server,
+ url: config.url,
+ usesOAuth: config.oauth === true,
+ bearerTokenEnvVar: config.bearerTokenEnvVar,
+ enabled: config.enabled,
+ headers: config.headers,
+ userDeclared: true,
+ });
+ }
+ this.integrations = integrations;
+ }
+
+ private registerProviders(): void {
+ registerBuiltinMcpOAuthProviders();
+ this.registerUserProviders();
+ }
+
+ /**
+ * Register OAuth providers for user-declared (non-catalog) servers. Public so it
+ * can run after ModelRegistry.refresh() resets the registry — otherwise custom
+ * `mcp:<server>` providers vanish on every refresh (e.g. post-login).
+ */
+ registerUserProviders(): void {
+ const current = new Set<string>();
+ for (const integration of this.integrations.values()) {
+ if (!integration.userDeclared) continue;
+ const id = this.providerId(integration.server);
+ if (integration.usesOAuth) {
+ // Register pointing at the user's URL (overrides a catalog default too).
+ current.add(id);
+ registerOAuthProvider(
+ createMcpOAuthProvider({
+ server: integration.server,
+ label: integration.label,
+ url: integration.url,
+ }),
+ );
+ } else if (getCatalogEntry(integration.server)) {
+ // User overrode a catalog server with a custom URL but no oauth: drop the
+ // built-in provider so we never send the official token to that URL.
+ unregisterOAuthProvider(id);
+ }
+ }
+ // Drop providers for user servers removed since the last registration.
+ for (const id of this.registeredUserProviderIds) {
+ if (!current.has(id)) unregisterOAuthProvider(id);
+ }
+ this.registeredUserProviderIds = current;
+ }
+
+ /** True when valid credentials exist for the integration (drives enablement). */
+ private isAuthed(integration: ResolvedIntegration): boolean {
+ if (integration.enabled === false) return false;
+ if (integration.bearerTokenEnvVar && process.env[integration.bearerTokenEnvVar]?.trim()) {
+ return true;
+ }
+ // A user server that overrides a catalog name must NOT inherit the built-in's
+ // stored mcp: creds — those were issued for the official endpoint and could be
+ // sent to the override URL. Such an override authenticates only via a bearer
+ // env var (handled above); we don't trust auth.json OAuth creds for it.
+ if (integration.userDeclared && getCatalogEntry(integration.server)) {
+ return false;
+ }
+ const cred = this.authStorage.get(this.providerId(integration.server));
+ return cred !== undefined;
+ }
+
+ /** `-<server>/SKILL.md` overrides for every built-in integration the user isn't logged into. */
+ getDisabledBuiltinSkillOverrides(): string[] {
+ const overrides: string[] = [];
+ for (const entry of BUILTIN_MCP_CATALOG) {
+ const integration = this.integrations.get(entry.server);
+ if (integration && !this.isAuthed(integration)) {
+ overrides.push(`-${entry.server}/SKILL.md`);
+ }
+ }
+ return overrides;
+ }
+
+ /** Host-request handlers exposed to the kernel. */
+ hostHandlers(): Record<string, (payload: Record<string, unknown>) => Promise<Record<string, unknown>>> {
+ const handlers: Record<string, (payload: Record<string, unknown>) => Promise<Record<string, unknown>>> = {
+ "mcp.refresh": async (payload) => {
+ const server = String(payload.server ?? "");
+ if (!server) throw new Error("mcp.refresh requires a server");
+ // getApiKey refreshes + rewrites auth.json under lock; Python re-reads.
+ // Surface failure (throw) instead of a false success so the kernel can
+ // report a refresh error rather than a misleading "not enabled".
+ const key = await this.authStorage.getApiKey(this.providerId(server));
+ if (!key) throw new Error(`Could not refresh credentials for ${server}`);
+ return {};
+ },
+ // Resolved config so the kernel skill connects to the same URL the host
+ // registered/authenticated (honors a user's mcpServers `url` override).
+ "mcp.config": async (payload) => {
+ const server = String(payload.server ?? "");
+ if (!server) throw new Error("mcp.config requires a server");
+ const integration = this.integrations.get(server);
+ if (!integration) return {};
+ const config: Record<string, unknown> = { url: integration.url };
+ if (integration.headers && Object.keys(integration.headers).length > 0) {
+ config.headers = integration.headers;
+ }
+ return config;
+ },
+ };
+ // Only expose begin_login when an interactive login is actually wired, so the
+ // kernel doesn't get a handler whose only behavior is to throw.
+ const beginLogin = this.beginLogin;
+ if (beginLogin) {
+ handlers["mcp.begin_login"] = async (payload) => {
+ const server = String(payload.server ?? "");
+ if (!server) throw new Error("mcp.begin_login requires a server");
+ await beginLogin(server);
+ return {};
+ };
+ }
+ return handlers;
+ }
+
+ /** Status for the /mcp list command. */
+ listStatus(): Array<{ server: string; label: string; enabled: boolean; usesOAuth: boolean }> {
+ return Array.from(this.integrations.values()).map((integration) => ({
+ server: integration.server,
+ label: integration.label,
+ enabled: this.isAuthed(integration),
+ usesOAuth: integration.usesOAuth,
+ }));
+ }
+}
diff --git a/packages/coding-agent/src/core/model-registry.ts b/packages/coding-agent/src/core/model-registry.ts
index 8b8ecefc70..032d5f7d63 100644
--- a/packages/coding-agent/src/core/model-registry.ts
+++ b/packages/coding-agent/src/core/model-registry.ts
@@ -18,6 +18,7 @@ import {
resetApiProviders,
type SimpleStreamOptions,
} from "@earendil-works/pi-ai";
+import { registerBuiltinMcpOAuthProviders } from "@earendil-works/pi-ai/mcp";
import { registerOAuthProvider, resetOAuthProviders } from "@earendil-works/pi-ai/oauth";
import { existsSync, readFileSync } from "fs";
import { join } from "path";
@@ -347,6 +348,9 @@ export class ModelRegistry {
private registeredProviders: Map<string, ProviderConfigInput> = new Map();
private loadError: string | undefined = undefined;
+ /** Re-register dynamic OAuth providers (e.g. user MCP servers) after refresh() resets the registry. */
+ private onOAuthProvidersReset?: () => void;
+
private constructor(
readonly authStorage: AuthStorage,
private modelsJsonPath: string | undefined,
@@ -354,6 +358,10 @@ export class ModelRegistry {
this.loadModels();
}
+ setOnOAuthProvidersReset(hook: () => void): void {
+ this.onOAuthProvidersReset = hook;
+ }
+
static create(authStorage: AuthStorage, modelsJsonPath: string = join(getAgentDir(), "models.json")): ModelRegistry {
return new ModelRegistry(authStorage, modelsJsonPath);
}
@@ -377,6 +385,15 @@ export class ModelRegistry {
// Ensure dynamic API/OAuth registrations are rebuilt from current provider state.
resetApiProviders();
resetOAuthProviders();
+ // reset drops everything but model-provider built-ins; re-add MCP integrations
+ // (built-in catalog + this session's user-declared servers via the hook).
+ // NOTE: the OAuth registry is process-global. Built-in MCP providers are
+ // identical across sessions so they always survive; a user-declared server
+ // unique to another daemon session is dropped here and re-registered on that
+ // session's next refresh. Fully isolating it would require a session-scoped
+ // registry in pi-ai (out of scope here).
+ registerBuiltinMcpOAuthProviders();
+ this.onOAuthProvidersReset?.();
this.loadModels();
diff --git a/packages/coding-agent/src/core/package-manager.ts b/packages/coding-agent/src/core/package-manager.ts
index 729ad52d99..e31620dc0a 100644
--- a/packages/coding-agent/src/core/package-manager.ts
+++ b/packages/coding-agent/src/core/package-manager.ts
@@ -115,6 +115,8 @@ interface PackageManagerOptions {
settingsManager: SettingsManager;
/** Directory of built-in skills shipped with the package. Defaults to the bundled skills dir; pass null to disable. */
bundledSkillsDir?: string | null;
+ /** Extra force-exclude patterns for built-in skills (e.g. unauthenticated MCP integrations). */
+ extraBuiltinSkillOverrides?: () => string[];
}
type SourceScope = "user" | "project" | "temporary";
@@ -766,6 +768,7 @@ export class DefaultPackageManager implements PackageManager {
private agentDir: string;
private settingsManager: SettingsManager;
private bundledSkillsDir: string | null;
+ private extraBuiltinSkillOverrides: () => string[];
private globalNpmRoot: string | undefined;
private globalNpmRootCommandKey: string | undefined;
private progressCallback: ProgressCallback | undefined;
@@ -775,6 +778,7 @@ export class DefaultPackageManager implements PackageManager {
this.agentDir = options.agentDir;
this.settingsManager = options.settingsManager;
this.bundledSkillsDir = options.bundledSkillsDir === undefined ? getBundledSkillsDir() : options.bundledSkillsDir;
+ this.extraBuiltinSkillOverrides = options.extraBuiltinSkillOverrides ?? (() => []);
}
setProgressCallback(callback: ProgressCallback | undefined): void {
@@ -2258,9 +2262,13 @@ export class DefaultPackageManager implements PackageManager {
path: this.bundledSkillsDir,
});
}
- const builtinSkillOverrides = this.settingsManager.getBundledWebsearchEnabled()
- ? userOverrides.skills
- : [...userOverrides.skills, "-websearch/SKILL.md"];
+ const builtinSkillOverrides = [
+ ...userOverrides.skills,
+ // Disable the bundled websearch skill unless explicitly enabled…
+ ...(this.settingsManager.getBundledWebsearchEnabled() ? [] : ["-websearch/SKILL.md"]),
+ // …and disable any MCP integration the user hasn't logged into.
+ ...this.extraBuiltinSkillOverrides(),
+ ];
addResources("skills", builtinEntries, builtinMetadata, builtinSkillOverrides, this.bundledSkillsDir);
}
addResources(
diff --git a/packages/coding-agent/src/core/resource-loader.ts b/packages/coding-agent/src/core/resource-loader.ts
index 565d7b0c18..b5f019b199 100644
--- a/packages/coding-agent/src/core/resource-loader.ts
+++ b/packages/coding-agent/src/core/resource-loader.ts
@@ -130,6 +130,8 @@ export interface DefaultResourceLoaderOptions {
noContextFiles?: boolean;
/** Directory of built-in skills shipped with the package. Defaults to the bundled skills dir; pass null to disable. */
bundledSkillsDir?: string | null;
+ /** Extra force-exclude patterns for built-in skills (e.g. unauthenticated MCP integrations). */
+ extraBuiltinSkillOverrides?: () => string[];
systemPrompt?: string;
appendSystemPrompt?: string[];
extensionsOverride?: (base: LoadExtensionsResult) => LoadExtensionsResult;
@@ -218,6 +220,7 @@ export class DefaultResourceLoader implements ResourceLoader {
agentDir: this.agentDir,
settingsManager: this.settingsManager,
bundledSkillsDir: this.bundledSkillsDir,
+ extraBuiltinSkillOverrides: options.extraBuiltinSkillOverrides,
});
this.additionalExtensionPaths = options.additionalExtensionPaths ?? [];
this.additionalSkillPaths = options.additionalSkillPaths ?? [];
diff --git a/packages/coding-agent/src/core/sdk.ts b/packages/coding-agent/src/core/sdk.ts
index 0e556cd96b..5cbc4ec961 100644
--- a/packages/coding-agent/src/core/sdk.ts
+++ b/packages/coding-agent/src/core/sdk.ts
@@ -8,6 +8,7 @@ import { formatNoModelsAvailableMessage } from "./auth-guidance.js";
import { AuthStorage } from "./auth-storage.js";
import { DEFAULT_THINKING_LEVEL } from "./defaults.js";
import type { ExtensionRunner, LoadExtensionsResult, SessionStartEvent, ToolDefinition } from "./extensions/index.js";
+import { McpManager } from "./mcp/mcp-manager.js";
import { convertToLlm } from "./messages.js";
import { ModelRegistry } from "./model-registry.js";
import { findInitialModel } from "./model-resolver.js";
@@ -58,6 +59,9 @@ export interface CreateAgentSessionOptions extends AgentSessionCreationOptions {
/** Resource loader. When omitted, DefaultResourceLoader is used. */
resourceLoader?: ResourceLoader;
+ /** MCP integration manager. When omitted, MCP host handlers are not wired. */
+ mcpManager?: McpManager;
+
/** Session manager. Default: SessionManager.create(cwd) */
sessionManager?: SessionManager;
@@ -159,8 +163,19 @@ export async function createAgentSession(options: CreateAgentSessionOptions = {}
const settingsManager = options.settingsManager ?? SettingsManager.create(cwd, agentDir);
const sessionManager = options.sessionManager ?? SessionManager.create(cwd, getDefaultSessionDir(cwd, agentDir));
+ // Ensure MCP providers are registered and built-in MCP skills are gated by
+ // auth even on the bare SDK path (not just the CLI's createAgentSessionServices).
+ const mcpManager =
+ options.mcpManager ?? new McpManager({ authStorage, getUserServers: () => settingsManager.getMcpServers() });
+ modelRegistry.setOnOAuthProvidersReset(() => mcpManager.registerUserProviders());
+
if (!resourceLoader) {
- resourceLoader = new DefaultResourceLoader({ cwd, agentDir, settingsManager });
+ resourceLoader = new DefaultResourceLoader({
+ cwd,
+ agentDir,
+ settingsManager,
+ extraBuiltinSkillOverrides: () => mcpManager.getDisabledBuiltinSkillOverrides(),
+ });
await resourceLoader.reload();
time("resourceLoader.reload");
}
@@ -348,6 +363,7 @@ export async function createAgentSession(options: CreateAgentSessionOptions = {}
resourceLoader,
customTools: options.customTools,
modelRegistry,
+ mcpManager,
initialActiveToolNames,
allowedToolNames,
includeGoals,
diff --git a/packages/coding-agent/src/core/settings-manager.ts b/packages/coding-agent/src/core/settings-manager.ts
index fdfed50a38..cf51456ab8 100644
--- a/packages/coding-agent/src/core/settings-manager.ts
+++ b/packages/coding-agent/src/core/settings-manager.ts
@@ -79,6 +79,36 @@ export type PackageSource =
themes?: string[];
};
+/**
+ * Remote/local MCP server an integration connects to. Built-in integrations
+ * (Linear/Notion) are defined in the ai/mcp catalog; this is for user-declared
+ * servers. The kernel-side integration package reads creds from auth.json
+ * (`mcp:<name>`); login/refresh run host-side.
+ */
+export type McpServerConfig =
+ | {
+ type: "http";
+ url: string;
+ headers?: Record<string, string>;
+ /** Env var holding a static bearer token (skips OAuth). */
+ bearerTokenEnvVar?: string;
+ /** Use the generic OAuth login flow for this server. */
+ oauth?: boolean;
+ /** Force-disable even when credentials exist. */
+ enabled?: boolean;
+ enabledTools?: string[];
+ disabledTools?: string[];
+ }
+ | {
+ type: "stdio";
+ command: string;
+ args?: string[];
+ env?: Record<string, string>;
+ enabled?: boolean;
+ enabledTools?: string[];
+ disabledTools?: string[];
+ };
+
export interface Settings {
onboardingCompleted?: boolean;
defaultProvider?: string;
@@ -98,6 +128,7 @@ export interface Settings {
quietStartup?: boolean;
shellCommandPrefix?: string; // Prefix prepended to every bash command (e.g., "shopt -s expand_aliases" for alias support)
npmCommand?: string[]; // Command used for npm package lookup/install operations, argv-style (e.g., ["mise", "exec", "node@20", "--", "npm"])
+ mcpServers?: Record<string, McpServerConfig>; // User-declared MCP servers (name → config); built-ins are in the ai/mcp catalog
packages?: PackageSource[]; // Array of npm/git package sources (string or object with filtering)
extensions?: string[]; // Array of local extension file paths or directories
skills?: string[]; // Array of local skill file paths or directories
@@ -1029,6 +1060,10 @@ export class SettingsManager {
return this.settings.enabledModels;
}
+ getMcpServers(): Record<string, McpServerConfig> | undefined {
+ return this.settings.mcpServers;
+ }
+
setEnabledModels(patterns: string[] | undefined): void {
this.globalSettings.enabledModels = patterns;
this.markModified("enabledModels");
diff --git a/packages/coding-agent/src/core/slash-commands.ts b/packages/coding-agent/src/core/slash-commands.ts
index 4492a4e2b1..bfeaf212d9 100644
--- a/packages/coding-agent/src/core/slash-commands.ts
+++ b/packages/coding-agent/src/core/slash-commands.ts
@@ -61,6 +61,7 @@ const CANONICAL_BUILTIN_SLASH_COMMANDS: ReadonlyArray<BuiltinSlashCommand> = [
{ name: "tree", description: "Navigate session tree (switch branches)" },
{ name: "login", description: "Configure provider authentication" },
{ name: "logout", description: "Remove provider authentication" },
+ { name: "mcp", description: "Manage MCP integrations (list, login <name>, logout <name>)" },
{ name: "new", description: "Start a new session" },
{
name: "compact",
diff --git a/packages/coding-agent/src/main.ts b/packages/coding-agent/src/main.ts
index 5525628f93..3510077cf6 100644
--- a/packages/coding-agent/src/main.ts
+++ b/packages/coding-agent/src/main.ts
@@ -8,6 +8,7 @@
import { join, resolve } from "node:path";
import { createInterface } from "node:readline";
import { type Api, type ImageContent, type Model, modelsAreEqual } from "@earendil-works/pi-ai";
+import { registerBuiltinMcpOAuthProviders } from "@earendil-works/pi-ai/mcp";
import { ProcessTerminal, setKeybindings, TUI } from "@earendil-works/pi-tui";
import chalk from "chalk";
import { type Args, type Mode, parseArgs, printHelp } from "./cli/args.js";
@@ -1006,6 +1007,8 @@ export interface MainOptions {
export async function main(args: string[], options?: MainOptions) {
resetTimings();
+ // Client and daemon are separate processes; both need these in their registry.
+ registerBuiltinMcpOAuthProviders();
args = normalizeDaemonStartArgs(args) ?? args;
const offlineMode = args.includes("--offline") || isTruthyEnvFlag(process.env.PI_OFFLINE);
if (offlineMode) {
diff --git a/packages/coding-agent/src/modes/interactive/auth-flows.ts b/packages/coding-agent/src/modes/interactive/auth-flows.ts
index 6249288df3..8a5c464d59 100644
--- a/packages/coding-agent/src/modes/interactive/auth-flows.ts
+++ b/packages/coding-agent/src/modes/interactive/auth-flows.ts
@@ -118,6 +118,23 @@ export class ProviderAuthFlows {
constructor(private readonly host: ProviderAuthFlowsHost) {}
/** Runs the provider selector followed by the matching login dialog. */
+ /**
+ * Run the OAuth login flow for an MCP integration server.
+ *
+ * The provider must already be registered (the McpManager does this as
+ * `mcp:<server>`). On success the credentials land in auth.json and the
+ * caller should reload resources so the integration's skill enables.
+ */
+ runMcpLogin(server: string, label?: string): Promise<AuthenticationResult> {
+ const providerId = `mcp:${server}`;
+ const provider = this.host.modelRegistry.authStorage.getOAuthProviders().find((p) => p.id === providerId);
+ if (!provider) {
+ this.host.showError(`Unknown MCP integration: ${server}`);
+ return Promise.resolve({ status: "failed" });
+ }
+ return this.showLoginDialog(providerId, label ?? provider.name, "service");
+ }
+
runLogin(authType?: "oauth" | "api_key"): Promise<AuthenticationResult> {
const providerOptions = this.getLoginProviderOptions(authType);
if (providerOptions.length === 0) {
@@ -145,7 +162,7 @@ export class ProviderAuthFlows {
close();
if (providerOption.authType === "oauth") {
- resolve(await this.showLoginDialog(providerOption.id, providerOption.name));
+ resolve(await this.showLoginDialog(providerOption.id, providerOption.name, providerOption.category));
} else if (providerOption.id === PRIME_INFERENCE_PROVIDER_ID) {
resolve(await this.runPrimeInferenceLogin());
} else if (providerOption.id === BEDROCK_PROVIDER_ID) {
@@ -167,13 +184,14 @@ export class ProviderAuthFlows {
}
/** Shows the stored-credential selector and removes the chosen credential. */
- runLogout(): Promise<void> {
+ /** Returns the provider id that was logged out, or null if nothing changed (cancelled / none). */
+ runLogout(): Promise<string | null> {
const providerOptions = this.getLogoutProviderOptions();
if (providerOptions.length === 0) {
this.host.showStatus(
"No stored credentials to remove. /logout only removes credentials saved by /login; environment variables and models.json config are unchanged.",
);
- return Promise.resolve();
+ return Promise.resolve(null);
}
return new Promise((resolve) => {
@@ -198,14 +216,15 @@ export class ProviderAuthFlows {
? `Logged out of ${providerOption.name}`
: `Removed stored API key for ${providerOption.name}. Environment variables and models.json config are unchanged.`;
this.host.showStatus(message);
+ resolve(providerOption.id);
} catch (error: unknown) {
this.host.showError(`Logout failed: ${error instanceof Error ? error.message : String(error)}`);
+ resolve(null);
}
- resolve();
},
() => {
close();
- resolve();
+ resolve(null);
},
undefined,
{ getRows: () => this.host.ui.terminal.rows },
@@ -222,6 +241,8 @@ export class ProviderAuthFlows {
id: provider.id,
name: provider.name,
authType: "oauth",
+ // MCP integrations (mcp:<server>) are services, not model providers.
+ ...(provider.id.startsWith("mcp:") ? { category: "service" as const } : {}),
}));
const modelProviders = new Set(this.host.modelRegistry.getAll().map((model) => model.provider));
@@ -252,17 +273,24 @@ export class ProviderAuthFlows {
const authStorage = this.host.modelRegistry.authStorage;
const options: AuthSelectorProvider[] = [];
+ const oauthProvidersById = new Map(authStorage.getOAuthProviders().map((p) => [p.id, p]));
for (const providerId of authStorage.list()) {
const credential = authStorage.get(providerId);
if (!credential) {
continue;
}
const isSerper = providerId === SERPER_CREDENTIAL_ID;
+ const isMcp = providerId.startsWith("mcp:");
+ const name = isSerper
+ ? SERPER_CREDENTIAL_NAME
+ : isMcp
+ ? (oauthProvidersById.get(providerId)?.name ?? providerId.slice("mcp:".length))
+ : this.host.modelRegistry.getProviderDisplayName(providerId);
options.push({
id: providerId,
- name: isSerper ? SERPER_CREDENTIAL_NAME : this.host.modelRegistry.getProviderDisplayName(providerId),
+ name,
authType: credential.type,
- category: isSerper ? "service" : "provider",
+ category: isSerper || isMcp ? "service" : "provider",
});
}
@@ -763,7 +791,11 @@ export class ProviderAuthFlows {
});
}
- private async showLoginDialog(providerId: string, providerName: string): Promise<AuthenticationResult> {
+ private async showLoginDialog(
+ providerId: string,
+ providerName: string,
+ kind: "provider" | "service" = "provider",
+ ): Promise<AuthenticationResult> {
const providerInfo = this.host.modelRegistry.authStorage
.getOAuthProviders()
.find((provider) => provider.id === providerId);
@@ -842,7 +874,7 @@ export class ProviderAuthFlows {
// Success
closeDialog();
- return await this.completeProviderAuthentication(providerId, providerName, "oauth");
+ return await this.completeProviderAuthentication(providerId, providerName, "oauth", undefined, kind);
} catch (error: unknown) {
closeDialog();
const errorMsg = error instanceof Error ? error.message : String(error);
diff --git a/packages/coding-agent/src/modes/interactive/interactive-mode.ts b/packages/coding-agent/src/modes/interactive/interactive-mode.ts
index e7be4af83b..06ce59d422 100644
--- a/packages/coding-agent/src/modes/interactive/interactive-mode.ts
+++ b/packages/coding-agent/src/modes/interactive/interactive-mode.ts
@@ -16,6 +16,7 @@ import {
type Model,
type ToolCall,
} from "@earendil-works/pi-ai";
+import { BUILTIN_MCP_CATALOG } from "@earendil-works/pi-ai/mcp";
import type {
AutocompleteItem,
AutocompleteProvider,
@@ -3598,6 +3599,11 @@ export class InteractiveMode {
await this.showOAuthSelector("logout");
return;
}
+ if (commandName === "mcp") {
+ this.editor.setText("");
+ await this.handleMcpCommand(commandArgs);
+ return;
+ }
if (commandName === "new" && !commandArgs) {
this.editor.setText("");
await this.handleClearCommand();
@@ -6590,6 +6596,65 @@ export class InteractiveMode {
return this.createAuthFlows().runLogin(authType);
}
+ private async handleMcpCommand(args: string | undefined): Promise<void> {
+ const [sub, server] = (args ?? "").trim().split(/\s+/);
+ const authStorage = this.modelRegistry.authStorage;
+ const isAuthed = (name: string) => authStorage.get(`mcp:${name}`) !== undefined;
+
+ if (!sub || sub === "list") {
+ const labels = new Map(BUILTIN_MCP_CATALOG.map((e) => [e.server, e.label]));
+ const names = new Set([...labels.keys(), ...Object.keys(this.settingsManager.getMcpServers() ?? {})]);
+ const lines = [...names].map((name) => {
+ const status = isAuthed(name) ? "connected" : "not connected";
+ return ` ${labels.get(name) ?? name} (${name}) — ${status}`;
+ });
+ this.showStatus(
+ `MCP integrations:\n${lines.join("\n")}\n\nUse /mcp login <name> to connect, /mcp logout <name> to disconnect.`,
+ );
+ return;
+ }
+
+ if (sub === "login") {
+ if (!server) {
+ this.showError("Usage: /mcp login <name> (e.g. /mcp login linear)");
+ return;
+ }
+ const result = await this.createAuthFlows().runMcpLogin(server);
+ if (result.status === "success") {
+ // Enabling the skill needs a reload, which is refused mid-turn; tell the
+ // user to /reload rather than silently leaving creds saved but inactive.
+ if (this.isAgentStreaming() || this.isAgentCompacting()) {
+ this.showStatus(`Connected ${server}. Run /reload (after the current turn) to activate it.`);
+ } else {
+ this.showStatus(`Connected ${server}. Reloading so the integration becomes available…`);
+ await this.handleReloadCommand();
+ }
+ }
+ return;
+ }
+
+ if (sub === "logout") {
+ if (!server) {
+ this.showError("Usage: /mcp logout <name>");
+ return;
+ }
+ if (!isAuthed(server)) {
+ this.showStatus(`${server} is not connected.`);
+ return;
+ }
+ authStorage.logout(`mcp:${server}`);
+ if (this.isAgentStreaming() || this.isAgentCompacting()) {
+ this.showStatus(`Disconnected ${server}. Run /reload (after the current turn) to fully unload it.`);
+ } else {
+ this.showStatus(`Disconnected ${server}. Reloading…`);
+ await this.handleReloadCommand();
+ }
+ return;
+ }
+
+ this.showError(`Unknown /mcp subcommand: ${sub}. Use list, login, or logout.`);
+ }
+
private async showOAuthSelector(mode: "login" | "logout"): Promise<void> {
if (mode === "login") {
const authResult = await this.showLoginProviderSelector();
@@ -6597,10 +6662,24 @@ export class InteractiveMode {
if (authResult.status === "success" && authResult.kind !== "service") {
await this.promptForModelSelection();
}
+ // An MCP integration login enables its skill, so reload resources — but a
+ // reload is refused mid-turn, so tell the user to /reload (matching /mcp login).
+ if (authResult.status === "success" && authResult.providerId.startsWith("mcp:")) {
+ if (this.isAgentStreaming() || this.isAgentCompacting()) {
+ this.showStatus("Connected. Run /reload (after the current turn) to activate the integration.");
+ } else {
+ await this.handleReloadCommand();
+ }
+ }
return;
}
- await this.createAuthFlows().runLogout();
+ // Only reload when an MCP integration was actually removed (its skill must
+ // be disabled); a cancelled or non-MCP logout needs no reload.
+ const loggedOut = await this.createAuthFlows().runLogout();
+ if (loggedOut?.startsWith("mcp:")) {
+ await this.handleReloadCommand();
+ }
}
// =========================================================================
diff --git a/packages/coding-agent/test/mcp-manager.test.ts b/packages/coding-agent/test/mcp-manager.test.ts
new file mode 100644
index 0000000000..366a207ee5
--- /dev/null
+++ b/packages/coding-agent/test/mcp-manager.test.ts
@@ -0,0 +1,179 @@
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { getOAuthProvider, resetOAuthProviders } from "@earendil-works/pi-ai/oauth";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { AuthStorage } from "../src/core/auth-storage.js";
+import { McpManager } from "../src/core/mcp/mcp-manager.js";
+import { ModelRegistry } from "../src/core/model-registry.js";
+import type { McpServerConfig } from "../src/core/settings-manager.js";
+
+describe("McpManager", () => {
+ let tempDir: string;
+ let authStorage: AuthStorage;
+
+ beforeEach(() => {
+ tempDir = mkdtempSync(join(tmpdir(), "mcp-mgr-"));
+ authStorage = AuthStorage.create(join(tempDir, "auth.json"));
+ resetOAuthProviders();
+ });
+
+ afterEach(() => {
+ resetOAuthProviders();
+ rmSync(tempDir, { recursive: true, force: true });
+ });
+
+ it("disables every built-in integration when no credentials exist", () => {
+ const manager = new McpManager({ authStorage });
+ const overrides = manager.getDisabledBuiltinSkillOverrides();
+ expect(overrides).toContain("-linear/SKILL.md");
+ expect(overrides).toContain("-notion/SKILL.md");
+ });
+
+ it("enables an integration once credentials are stored", () => {
+ authStorage.set("mcp:linear", {
+ type: "oauth",
+ access: "tok",
+ refresh: "r",
+ expires: Date.now() + 3600_000,
+ });
+ const manager = new McpManager({ authStorage });
+ const overrides = manager.getDisabledBuiltinSkillOverrides();
+ expect(overrides).not.toContain("-linear/SKILL.md");
+ expect(overrides).toContain("-notion/SKILL.md");
+
+ const status = manager.listStatus().find((s) => s.server === "linear");
+ expect(status?.enabled).toBe(true);
+ });
+
+ it("registers an OAuth provider per built-in integration", () => {
+ new McpManager({ authStorage });
+ expect(getOAuthProvider("mcp:linear")).toBeDefined();
+ expect(getOAuthProvider("mcp:notion")).toBeDefined();
+ });
+
+ it("keeps MCP providers registered after ModelRegistry.refresh() resets the registry", () => {
+ new McpManager({ authStorage });
+ const registry = ModelRegistry.create(authStorage, join(tempDir, "models.json"));
+ registry.refresh(); // calls resetOAuthProviders(); must re-add MCP providers
+ expect(getOAuthProvider("mcp:linear")).toBeDefined();
+ expect(getOAuthProvider("mcp:notion")).toBeDefined();
+ });
+
+ it("re-registers user-declared OAuth servers after ModelRegistry.refresh via the reset hook", () => {
+ const manager = new McpManager({
+ authStorage,
+ getUserServers: () => ({ acme: { type: "http", url: "https://mcp.acme.test/mcp", oauth: true } }),
+ });
+ const registry = ModelRegistry.create(authStorage, join(tempDir, "models.json"));
+ registry.setOnOAuthProvidersReset(() => manager.registerUserProviders());
+ expect(getOAuthProvider("mcp:acme")).toBeDefined();
+ registry.refresh(); // resets registry; hook must re-add the custom provider
+ expect(getOAuthProvider("mcp:acme")).toBeDefined();
+ });
+
+ it("exposes only mcp.refresh when no interactive login is wired", async () => {
+ const manager = new McpManager({ authStorage });
+ const handlers = manager.hostHandlers();
+ expect(Object.keys(handlers).sort()).toEqual(["mcp.config", "mcp.refresh"]);
+
+ // refresh with no credentials fails (so the kernel reports a refresh error,
+ // not a false success), and a missing server arg is rejected.
+ await expect(handlers["mcp.refresh"]({ server: "linear" })).rejects.toThrow("Could not refresh");
+ await expect(handlers["mcp.refresh"]({})).rejects.toThrow("requires a server");
+ });
+
+ it("exposes mcp.begin_login only when beginLogin is provided", async () => {
+ let called = "";
+ const manager = new McpManager({
+ authStorage,
+ beginLogin: async (server) => {
+ called = server;
+ },
+ });
+ const handlers = manager.hostHandlers();
+ expect(Object.keys(handlers).sort()).toEqual(["mcp.begin_login", "mcp.config", "mcp.refresh"]);
+ await handlers["mcp.begin_login"]({ server: "linear" });
+ expect(called).toBe("linear");
+ });
+
+ it("mcp.config returns the resolved URL + headers, honoring a user override of a catalog name", async () => {
+ const manager = new McpManager({
+ authStorage,
+ getUserServers: () => ({
+ linear: { type: "http", url: "https://proxy.test/mcp", oauth: true, headers: { "X-Extra": "1" } },
+ }),
+ });
+ const handlers = manager.hostHandlers();
+ expect(await handlers["mcp.config"]({ server: "linear" })).toEqual({
+ url: "https://proxy.test/mcp",
+ headers: { "X-Extra": "1" },
+ });
+ expect(await handlers["mcp.config"]({ server: "notion" })).toEqual({ url: "https://mcp.notion.com/mcp" });
+ });
+
+ it("does not treat an oauth override of a catalog name as authed via the official stored cred", () => {
+ // Pre-existing official Linear cred from a prior login.
+ authStorage.set("mcp:linear", {
+ type: "oauth",
+ access: "official",
+ refresh: "r",
+ expires: Date.now() + 3600_000,
+ });
+ const manager = new McpManager({
+ authStorage,
+ getUserServers: () => ({ linear: { type: "http", url: "https://proxy.test/mcp", oauth: true } }),
+ });
+ // Must NOT be enabled — else the official token would be sent to the override URL.
+ expect(manager.listStatus().find((s) => s.server === "linear")?.enabled).toBe(false);
+ });
+
+ it("honors a bearer-token env var for user-declared servers", () => {
+ process.env.MY_MCP_TOKEN = "secret";
+ try {
+ const manager = new McpManager({
+ authStorage,
+ getUserServers: () => ({
+ custom: { type: "http", url: "https://example.test/mcp", bearerTokenEnvVar: "MY_MCP_TOKEN" },
+ }),
+ });
+ const status = manager.listStatus().find((s) => s.server === "custom");
+ expect(status?.enabled).toBe(true);
+ } finally {
+ delete process.env.MY_MCP_TOKEN;
+ }
+ });
+
+ it("picks up mcpServers added after construction on refresh()", () => {
+ let servers: Record<string, McpServerConfig> = {};
+ const manager = new McpManager({ authStorage, getUserServers: () => servers });
+ expect(manager.listStatus().find((s) => s.server === "acme")).toBeUndefined();
+
+ servers = { acme: { type: "http", url: "https://mcp.acme.test/mcp", oauth: true } };
+ manager.refresh();
+ expect(manager.listStatus().find((s) => s.server === "acme")).toBeDefined();
+ expect(getOAuthProvider("mcp:acme")).toBeDefined();
+ });
+
+ it("drops the built-in provider when a catalog name is overridden without oauth", () => {
+ const manager = new McpManager({
+ authStorage,
+ getUserServers: () => ({ linear: { type: "http", url: "https://proxy.test/mcp" } }),
+ });
+ void manager;
+ // Built-in linear provider must be gone so we don't send the official token to the override URL.
+ expect(getOAuthProvider("mcp:linear")).toBeUndefined();
+ });
+
+ it("unregisters a user server's OAuth provider when it's removed on refresh()", () => {
+ let servers: Record<string, McpServerConfig> = {
+ acme: { type: "http", url: "https://mcp.acme.test/mcp", oauth: true },
+ };
+ const manager = new McpManager({ authStorage, getUserServers: () => servers });
+ expect(getOAuthProvider("mcp:acme")).toBeDefined();
+
+ servers = {};
+ manager.refresh();
+ expect(getOAuthProvider("mcp:acme")).toBeUndefined();
+ });
+});
diff --git a/packages/coding-agent/test/settings-manager.test.ts b/packages/coding-agent/test/settings-manager.test.ts
index 2d2d15a3a5..20c72c73a6 100644
--- a/packages/coding-agent/test/settings-manager.test.ts
+++ b/packages/coding-agent/test/settings-manager.test.ts
@@ -361,4 +361,37 @@ describe("SettingsManager", () => {
expect(manager.getSessionDir()).toBe(join(homedir(), "sessions"));
});
});
+
+ describe("mcpServers", () => {
+ it("returns undefined when unset", () => {
+ writeFileSync(join(agentDir, "settings.json"), JSON.stringify({ theme: "dark" }));
+ const manager = SettingsManager.create(projectDir, agentDir);
+ expect(manager.getMcpServers()).toBeUndefined();
+ });
+
+ it("merges global and project mcpServers, project winning per key", () => {
+ writeFileSync(
+ join(agentDir, "settings.json"),
+ JSON.stringify({
+ mcpServers: {
+ acme: { type: "http", url: "https://global.acme/mcp", oauth: true },
+ shared: { type: "http", url: "https://global.shared/mcp" },
+ },
+ }),
+ );
+ writeFileSync(
+ join(projectDir, ".prime", "agent", "settings.json"),
+ JSON.stringify({
+ mcpServers: {
+ shared: { type: "http", url: "https://project.shared/mcp" },
+ },
+ }),
+ );
+ const manager = SettingsManager.create(projectDir, agentDir);
+ const servers = manager.getMcpServers();
+ expect(servers?.acme).toEqual({ type: "http", url: "https://global.acme/mcp", oauth: true });
+ // Project override replaces the shared entry.
+ expect(servers?.shared).toEqual({ type: "http", url: "https://project.shared/mcp" });
+ });
+ });
});
diff --git a/packages/coding-agent/vitest.config.ts b/packages/coding-agent/vitest.config.ts
index 67ce0fca83..7fff537154 100644
--- a/packages/coding-agent/vitest.config.ts
+++ b/packages/coding-agent/vitest.config.ts
@@ -3,6 +3,7 @@ import { defineConfig } from "vitest/config";
const aiSrcIndex = fileURLToPath(new URL("../ai/src/index.ts", import.meta.url));
const aiSrcOAuth = fileURLToPath(new URL("../ai/src/oauth.ts", import.meta.url));
+const aiSrcMcp = fileURLToPath(new URL("../ai/src/mcp.ts", import.meta.url));
const agentSrcIndex = fileURLToPath(new URL("../agent/src/index.ts", import.meta.url));
const tuiSrcIndex = fileURLToPath(new URL("../tui/src/index.ts", import.meta.url));
@@ -21,10 +22,12 @@ export default defineConfig({
alias: [
{ find: /^@earendil-works\/pi-ai$/, replacement: aiSrcIndex },
{ find: /^@earendil-works\/pi-ai\/oauth$/, replacement: aiSrcOAuth },
+ { find: /^@earendil-works\/pi-ai\/mcp$/, replacement: aiSrcMcp },
{ find: /^@earendil-works\/pi-agent-core$/, replacement: agentSrcIndex },
{ find: /^@earendil-works\/pi-tui$/, replacement: tuiSrcIndex },
{ find: /^@mariozechner\/pi-ai$/, replacement: aiSrcIndex },
{ find: /^@mariozechner\/pi-ai\/oauth$/, replacement: aiSrcOAuth },
+ { find: /^@mariozechner\/pi-ai\/mcp$/, replacement: aiSrcMcp },
{ find: /^@mariozechner\/pi-agent-core$/, replacement: agentSrcIndex },
{ find: /^@mariozechner\/pi-tui$/, replacement: tuiSrcIndex },
],
diff --git a/prime-agent-runtime/src/rlm/__init__.py b/prime-agent-runtime/src/rlm/__init__.py
index 43236a4d3b..91ccc4032c 100644
--- a/prime-agent-runtime/src/rlm/__init__.py
+++ b/prime-agent-runtime/src/rlm/__init__.py
@@ -198,6 +198,9 @@ sys.modules[__name__].__class__ = _CallableModule
__all__ = [
"HarnessEntry",
"HarnessState",
+ "McpIntegration",
+ "McpToolError",
+ "NotEnabled",
"RLMResult",
"RefinementEvent",
"TokenUsage",
@@ -207,3 +210,15 @@ __all__ = [
"rlm",
"run",
]
+
+# Lazily re-export the MCP base class. Kept lazy so `import rlm` never requires
+# the optional `mcp` SDK — only integration packages that subclass it do.
+_LAZY_MCP = {"McpIntegration", "McpToolError", "NotEnabled"}
+
+
+def __getattr__(name: str) -> Any: # noqa: D401 - module-level lazy attr hook
+ if name in _LAZY_MCP:
+ from . import mcp_base
+
+ return getattr(mcp_base, name)
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
diff --git a/prime-agent-runtime/src/rlm/mcp_base.py b/prime-agent-runtime/src/rlm/mcp_base.py
new file mode 100644
index 0000000000..740df3e99e
--- /dev/null
+++ b/prime-agent-runtime/src/rlm/mcp_base.py
@@ -0,0 +1,331 @@
+"""Base class for MCP-client integrations exposed in the RLM kernel.
+
+An integration is a Python skill package that subclasses :class:`McpIntegration`,
+declares the MCP ``server`` it targets, and is imported in the kernel like any
+other skill. Tools are auto-discovered from the server and bound as async
+methods, so the agent writes ordinary Python:
+
+ import linear
+ issues = await linear.list_issues(team="Engineering")
+
+Credentials live in the host's ``auth.json`` (single store, survives kernel
+rebuilds). This module reads that file directly for the common case; on token
+expiry it asks the host to refresh via ``rlm.host_request("mcp.refresh", ...)``
+and re-reads. Interactive login runs host-side, never here.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import os
+import time
+from contextlib import AsyncExitStack
+from pathlib import Path
+from typing import Any
+
+from . import host_request
+
+__all__ = ["McpIntegration", "McpToolError", "NotEnabled"]
+
+# Stored access tokens are treated as expired this many seconds early so a token
+# never dies mid-request. Mirrors the host's refresh buffer.
+_EXPIRY_SKEW_SECONDS = 30
+
+
+class NotEnabled(RuntimeError):
+ """Raised when an integration has no usable credentials.
+
+ The integration is installed but not logged in. The message tells the agent
+ how to enable it so it can relay that to the user rather than retrying.
+ """
+
+ def __init__(self, server: str):
+ self.server = server
+ super().__init__(
+ f"The '{server}' integration is not enabled: no credentials found. "
+ f"Tell the user to run `/mcp login {server}` in Prime Agent to connect it. "
+ f"Do not ask them to set environment variables."
+ )
+
+
+class McpToolError(RuntimeError):
+ """Raised when an MCP tool call returns a result flagged as an error."""
+
+
+def _agent_dir() -> Path:
+ """Resolve the Prime Agent config dir the same way the rest of the runtime does."""
+ raw = (
+ os.environ.get("PRIME_AGENT_CODING_AGENT_DIR")
+ or os.environ.get("PI_CODING_AGENT_DIR")
+ or str(Path.home() / ".prime" / "agent")
+ )
+ # resolve() so a relative env override reads auth.json from the right place,
+ # not relative to the kernel's cwd.
+ return Path(raw).expanduser().resolve()
+
+
+def _read_auth(provider: str) -> dict[str, Any] | None:
+ """Read one credential entry from auth.json. Returns None if absent/unreadable."""
+ try:
+ data = json.loads((_agent_dir() / "auth.json").read_text())
+ except (OSError, ValueError):
+ return None
+ if not isinstance(data, dict):
+ return None
+ cred = data.get(provider)
+ return cred if isinstance(cred, dict) else None
+
+
+def _resolve_config_value(value: str) -> str:
+ """Resolve a stored api_key value the way the host does.
+
+ A value may be a literal, an env-var name, or a `!command` indirection. The
+ command form can't run safely in the kernel (the host injects those resolved),
+ so skip it; otherwise treat the value as an env-var name if set, else literal.
+ """
+ value = value.strip()
+ if not value or value.startswith("!"):
+ return ""
+ return (os.environ.get(value) or value).strip()
+
+
+def _resolve_streamable_http():
+ """Return an SDK streamable-HTTP transport callable.
+
+ SDK versions vary: some expose ``streamablehttp_client(url, headers=...)``,
+ others ``streamable_http_client(url, *, http_client=...)``, and some expose
+ both with *different* signatures. Imported lazily so importing an integration
+ package never hard-fails when ``mcp`` is absent.
+ """
+ from mcp.client import streamable_http as mod # noqa: PLC0415
+
+ for name in ("streamablehttp_client", "streamable_http_client"):
+ fn = getattr(mod, name, None)
+ if fn is not None:
+ return fn
+ raise ImportError(
+ "the installed `mcp` SDK exposes no streamable-HTTP client; upgrade `mcp`"
+ )
+
+
+class McpIntegration:
+ """Subclass and set :attr:`server` (and :attr:`url` for remote servers).
+
+ Tools are discovered on first use and bound as async methods via
+ ``__getattr__``; ``await self.call_tool(name, args)`` is the explicit escape
+ hatch and the hook for hand-written typed wrappers.
+ """
+
+ #: Credential / config key for this integration (matches the auth.json entry
+ #: ``mcp:<server>`` and the mcpServers settings key).
+ server: str = ""
+
+ #: Remote MCP endpoint. Required unless a subclass overrides ``_open_streams``.
+ url: str | None = None
+
+ #: Optional env var holding a static bearer token (used instead of auth.json OAuth).
+ bearer_token_env: str | None = None
+
+ def __init__(self) -> None:
+ if not self.server:
+ raise ValueError(f"{type(self).__name__} must set a non-empty `server`")
+ self._tools: dict[str, Any] | None = None
+ self._lock = asyncio.Lock()
+
+ # -- credentials --------------------------------------------------------
+
+ @property
+ def _provider_id(self) -> str:
+ return f"mcp:{self.server}"
+
+ def _token(self) -> str | None:
+ """Current usable bearer token, or None if missing/expired (needs refresh).
+
+ A static bearer-token env var wins (matches the host's `isAuthed` check);
+ otherwise read auth.json. OAuth tokens are only returned while still fresh.
+ """
+ if self.bearer_token_env:
+ env_token = os.environ.get(self.bearer_token_env, "").strip()
+ if env_token:
+ return env_token
+ cred = _read_auth(self._provider_id)
+ if cred is None:
+ return None
+ if cred.get("type") == "api_key":
+ return _resolve_config_value(str(cred.get("key") or "")) or None
+ # OAuth credential: {access, refresh, expires(ms)}.
+ access = str(cred.get("access") or "")
+ expires = cred.get("expires")
+ fresh = isinstance(expires, (int, float)) and (
+ time.time() * 1000 < expires - _EXPIRY_SKEW_SECONDS * 1000
+ )
+ if access and fresh:
+ return access
+ return None # signal: needs refresh
+
+ async def _resolve_token(self) -> str:
+ token = self._token()
+ if token:
+ return token
+ # Expired or missing-access: ask the host to refresh, then re-validate via
+ # _token() (which re-checks expiry) rather than trusting any access value.
+ if _read_auth(self._provider_id) is not None:
+ refresh_error: Exception | None = None
+ try:
+ await host_request("mcp.refresh", {"server": self.server})
+ except RuntimeError as exc:
+ refresh_error = exc
+ token = self._token()
+ if token:
+ return token
+ # A refresh that failed (vs. genuinely-absent creds) is a recoverable
+ # error; don't mislabel it as "not enabled / re-login".
+ if refresh_error is not None:
+ raise RuntimeError(
+ f"Failed to refresh credentials for '{self.server}': {refresh_error}"
+ ) from refresh_error
+ raise NotEnabled(self.server)
+
+ # -- connection ---------------------------------------------------------
+
+ async def _resolve_config(self) -> tuple[str | None, dict[str, str]]:
+ """Host-resolved (url, extra_headers), honoring a user's mcpServers override.
+ Falls back to the class ``url`` and no extra headers on host error."""
+ try:
+ cfg = await host_request("mcp.config", {"server": self.server})
+ except RuntimeError:
+ cfg = {}
+ url = cfg.get("url") if isinstance(cfg, dict) else None
+ headers = cfg.get("headers") if isinstance(cfg, dict) else None
+ if not (isinstance(url, str) and url):
+ url = self.url
+ extra = headers if isinstance(headers, dict) else {}
+ return url, {str(k): str(v) for k, v in extra.items()}
+
+ async def _open_session(self, stack: AsyncExitStack):
+ """Open an initialized MCP ClientSession bound to ``stack``.
+
+ Override for non-HTTP transports (e.g. stdio). The default connects over
+ streamable HTTP with a Bearer token from auth.json. The URL comes from the
+ host (mcpServers override) when available, else ``self.url``.
+ """
+ import inspect # noqa: PLC0415
+
+ from mcp import ClientSession # noqa: PLC0415
+
+ url, extra_headers = await self._resolve_config()
+ if not url:
+ raise ValueError(
+ f"{type(self).__name__} must set `url` or override `_open_session`"
+ )
+ token = await self._resolve_token()
+ transport = _resolve_streamable_http()
+ # Extra configured headers first, Authorization last so it always wins.
+ auth_header = {**extra_headers, "Authorization": f"Bearer {token}"}
+
+ # SDK signatures vary: some take headers=, others only http_client=.
+ params = inspect.signature(transport).parameters
+ if "headers" in params:
+ cm = transport(url, headers=auth_header)
+ elif "http_client" in params:
+ import httpx # noqa: PLC0415
+
+ client = await stack.enter_async_context(httpx.AsyncClient(headers=auth_header))
+ cm = transport(url, http_client=client)
+ else:
+ raise RuntimeError(
+ f"unsupported mcp streamable-HTTP client signature: {tuple(params)}"
+ )
+
+ read, write, *_ = await stack.enter_async_context(cm)
+ session = await stack.enter_async_context(ClientSession(read, write))
+ await session.initialize()
+ return session
+
+ # -- tools --------------------------------------------------------------
+
+ async def list_tools(self) -> list[dict[str, Any]]:
+ """Return the server's tools as ``[{name, description, inputSchema}]``."""
+ await self._ensure_tools()
+ return [dict(t) for t in (self._tools or {}).values()]
+
+ async def _ensure_tools(self) -> None:
+ if self._tools is not None:
+ return
+ async with self._lock:
+ if self._tools is not None:
+ return
+ async with AsyncExitStack() as stack:
+ session = await self._open_session(stack)
+ resp = await session.list_tools()
+ self._tools = {
+ t.name: {
+ "name": t.name,
+ "description": getattr(t, "description", "") or "",
+ "inputSchema": getattr(t, "inputSchema", None) or {},
+ }
+ for t in resp.tools
+ }
+
+ async def call_tool(self, tool: str, arguments: dict[str, Any] | None = None) -> Any:
+ """Call ``tool`` on the server and return its parsed result.
+
+ Opens a fresh session per call: MCP sessions are not safe to hold across
+ the kernel's snapshot/restore, and per-call connect keeps this robust to
+ idle sessions and token rotation at modest latency cost.
+ """
+ async with AsyncExitStack() as stack:
+ session = await self._open_session(stack)
+ result = await session.call_tool(tool, arguments or {})
+ return _parse_result(result)
+
+ def __getattr__(self, name: str):
+ # Only reached for names not found normally; bind as an async tool call.
+ if name.startswith("_"):
+ raise AttributeError(name)
+
+ async def _call(**kwargs: Any) -> Any:
+ await self._ensure_tools()
+ if self._tools is not None and name not in self._tools:
+ available = ", ".join(sorted(self._tools)) or "(none)"
+ raise AttributeError(
+ f"'{self.server}' has no tool '{name}'. Available: {available}"
+ )
+ return await self.call_tool(name, kwargs)
+
+ _call.__name__ = name
+ _call.__qualname__ = f"{type(self).__name__}.{name}"
+ if self._tools and name in self._tools:
+ schema = self._tools[name].get("inputSchema") or {}
+ desc = self._tools[name].get("description") or ""
+ _call.__doc__ = f"{desc}\n\nArguments (JSON Schema):\n{json.dumps(schema, indent=2)}"
+ return _call
+
+
+def _parse_result(result: Any) -> Any:
+ """Normalize a CallToolResult into plain Python (structured output preferred).
+
+ Raises McpToolError when the server flags the result as an error, so a failed
+ tool call doesn't look like a successful one to the caller.
+ """
+ texts: list[str] = []
+ for block in getattr(result, "content", None) or []:
+ text = getattr(block, "text", None)
+ if text is not None:
+ texts.append(text)
+ if getattr(result, "isError", False):
+ raise McpToolError("\n".join(texts) or "MCP tool returned an error")
+
+ structured = getattr(result, "structuredContent", None)
+ if structured is not None: # falsy-but-valid payloads ({} / []) are real results
+ return structured
+ if texts:
+ return "\n".join(texts)
+
+ # Non-text content (images, embedded resources): return them as plain dicts
+ # rather than the opaque SDK object so callers get usable data.
+ blocks = getattr(result, "content", None) or []
+ if blocks:
+ return [b.model_dump(mode="json") if hasattr(b, "model_dump") else b for b in blocks]
+ return result
diff --git a/prime-agent-runtime/test/test_mcp_base.py b/prime-agent-runtime/test/test_mcp_base.py
new file mode 100644
index 0000000000..7f31c565bb
--- /dev/null
+++ b/prime-agent-runtime/test/test_mcp_base.py
@@ -0,0 +1,274 @@
+from __future__ import annotations
+
+import asyncio
+import json
+import tempfile
+import time
+import unittest
+from contextlib import AsyncExitStack
+from pathlib import Path
+from unittest import mock
+
+from rlm import mcp_base
+from rlm.mcp_base import McpIntegration, McpToolError, NotEnabled
+
+
+def _run(coro):
+ return asyncio.run(coro)
+
+
+class _FakeSession:
+ """Stand-in for an mcp ClientSession with canned tools/results."""
+
+ def __init__(self, tools, result):
+ self._tools = tools
+ self._result = result
+ self.calls = []
+
+ async def list_tools(self):
+ Tool = type("Tool", (), {})
+
+ def make(name, desc, schema):
+ t = Tool()
+ t.name = name
+ t.description = desc
+ t.inputSchema = schema
+ return t
+
+ resp = type("Resp", (), {})()
+ resp.tools = [make(*t) for t in self._tools]
+ return resp
+
+ async def call_tool(self, name, arguments):
+ self.calls.append((name, arguments))
+ return self._result
+
+
+class _Integration(McpIntegration):
+ server = "demo"
+ url = "https://example.test/mcp"
+
+
+class McpIntegrationTest(unittest.TestCase):
+ def setUp(self):
+ self._tmp = tempfile.TemporaryDirectory()
+ self.agent_dir = Path(self._tmp.name)
+ self.auth_path = self.agent_dir / "auth.json"
+ patcher = mock.patch.object(mcp_base, "_agent_dir", return_value=self.agent_dir)
+ patcher.start()
+ self.addCleanup(patcher.stop)
+ self.addCleanup(self._tmp.cleanup)
+
+ def _write_auth(self, cred):
+ self.auth_path.write_text(json.dumps({"mcp:demo": cred}))
+
+ def _patch_session(self, session):
+ # Replace _open_session so no real network/SDK is needed.
+ async def fake_open(self_, stack: AsyncExitStack):
+ return session
+
+ return mock.patch.object(_Integration, "_open_session", fake_open)
+
+ def test_not_enabled_without_credentials(self):
+ integration = _Integration()
+ with self.assertRaises(NotEnabled):
+ _run(integration._resolve_token())
+
+ def test_reads_oauth_access_token(self):
+ self._write_auth(
+ {"type": "oauth", "access": "tok-123", "refresh": "r", "expires": (time.time() + 3600) * 1000}
+ )
+ self.assertEqual(_run(_Integration()._resolve_token()), "tok-123")
+
+ def test_reads_api_key(self):
+ self._write_auth({"type": "api_key", "key": "key-abc"})
+ self.assertEqual(_run(_Integration()._resolve_token()), "key-abc")
+
+ def test_api_key_env_indirection_resolved(self):
+ self._write_auth({"type": "api_key", "key": "MY_MCP_KEY"})
+ with mock.patch.dict("os.environ", {"MY_MCP_KEY": "resolved-secret"}):
+ self.assertEqual(_run(_Integration()._resolve_token()), "resolved-secret")
+
+ def test_refreshes_via_host_when_expired(self):
+ self._write_auth(
+ {"type": "oauth", "access": "old", "refresh": "r", "expires": (time.time() - 10) * 1000}
+ )
+
+ async def fake_host_request(req_type, payload):
+ self.assertEqual(req_type, "mcp.refresh")
+ self.assertEqual(payload, {"server": "demo"})
+ # Simulate the host rewriting auth.json with a fresh token.
+ self._write_auth(
+ {"type": "oauth", "access": "new", "refresh": "r", "expires": (time.time() + 3600) * 1000}
+ )
+ return {}
+
+ with mock.patch.object(mcp_base, "host_request", fake_host_request):
+ self.assertEqual(_run(_Integration()._resolve_token()), "new")
+
+ def test_not_enabled_when_refresh_leaves_token_expired(self):
+ # Host refresh "succeeds" but auth.json still holds an expired token →
+ # must raise NotEnabled, not return the stale access value.
+ self._write_auth(
+ {"type": "oauth", "access": "stale", "refresh": "r", "expires": (time.time() - 10) * 1000}
+ )
+
+ async def fake_host_request(req_type, payload):
+ return {} # no-op: token stays expired
+
+ with mock.patch.object(mcp_base, "host_request", fake_host_request):
+ with self.assertRaises(NotEnabled):
+ _run(_Integration()._resolve_token())
+
+ def test_refresh_failure_surfaces_as_error_not_not_enabled(self):
+ # Creds exist but the host refresh fails transiently → surface a refresh
+ # error, not a misleading NotEnabled (which implies re-login).
+ self._write_auth(
+ {"type": "oauth", "access": "stale", "refresh": "r", "expires": (time.time() - 10) * 1000}
+ )
+
+ async def failing_host_request(req_type, payload):
+ raise RuntimeError("network down")
+
+ with mock.patch.object(mcp_base, "host_request", failing_host_request):
+ with self.assertRaises(RuntimeError) as ctx:
+ _run(_Integration()._resolve_token())
+ self.assertNotIsInstance(ctx.exception, NotEnabled)
+ self.assertIn("refresh", str(ctx.exception).lower())
+
+ def test_bearer_token_env_wins(self):
+ class EnvIntegration(_Integration):
+ bearer_token_env = "DEMO_MCP_TOKEN"
+
+ with mock.patch.dict("os.environ", {"DEMO_MCP_TOKEN": "env-secret"}):
+ self.assertEqual(_run(EnvIntegration()._resolve_token()), "env-secret")
+
+ def test_empty_structured_result_preserved(self):
+ for payload in ({}, []):
+ result = type("R", (), {"structuredContent": payload, "content": [], "isError": False})()
+ self.assertEqual(mcp_base._parse_result(result), payload)
+
+ def test_error_result_raises(self):
+ block = type("B", (), {"text": "boom"})()
+ result = type("R", (), {"isError": True, "content": [block], "structuredContent": None})()
+ with self.assertRaises(McpToolError) as ctx:
+ mcp_base._parse_result(result)
+ self.assertIn("boom", str(ctx.exception))
+
+ def test_auto_bound_tool_calls_session(self):
+ session = _FakeSession(
+ tools=[("list_issues", "List issues", {"type": "object"})],
+ result=type("R", (), {"structuredContent": {"issues": [1, 2]}})(),
+ )
+ self._write_auth(
+ {"type": "oauth", "access": "t", "refresh": "r", "expires": (time.time() + 3600) * 1000}
+ )
+ with self._patch_session(session):
+ integration = _Integration()
+ out = _run(integration.list_issues(team="Eng"))
+ self.assertEqual(out, {"issues": [1, 2]})
+ self.assertEqual(session.calls, [("list_issues", {"team": "Eng"})])
+
+ def test_unknown_tool_raises_with_available_list(self):
+ session = _FakeSession(tools=[("list_issues", "", {})], result=None)
+ self._write_auth(
+ {"type": "oauth", "access": "t", "refresh": "r", "expires": (time.time() + 3600) * 1000}
+ )
+ with self._patch_session(session):
+ integration = _Integration()
+ with self.assertRaises(AttributeError) as ctx:
+ _run(integration.nonexistent_tool())
+ self.assertIn("list_issues", str(ctx.exception))
+
+ def test_text_result_parsing(self):
+ block = type("B", (), {"text": "hello"})()
+ result = type("R", (), {"content": [block], "structuredContent": None})()
+ self.assertEqual(mcp_base._parse_result(result), "hello")
+
+ def test_requires_server_attribute(self):
+ class Bad(McpIntegration):
+ server = ""
+
+ with self.assertRaises(ValueError):
+ Bad()
+
+ def _run_open_session_with_transport(self, transport):
+ """Drive the real _open_session against a fake transport callable.
+
+ `transport` must declare its real parameters (headers= or http_client=)
+ so the signature inspection in _open_session is exercised faithfully.
+ """
+ self._write_auth(
+ {"type": "oauth", "access": "tok-xyz", "refresh": "r", "expires": (time.time() + 3600) * 1000}
+ )
+
+ async def fake_host_request(req_type, payload):
+ return {} # no host URL override; _resolve_url falls back to self.url
+
+ with mock.patch.object(mcp_base, "host_request", fake_host_request), \
+ mock.patch.object(mcp_base, "_resolve_streamable_http", lambda: transport), \
+ mock.patch("mcp.ClientSession") as session_cls:
+ session = mock.MagicMock()
+ session.initialize = mock.AsyncMock()
+ session.call_tool = mock.AsyncMock(
+ return_value=type("R", (), {"content": [], "structuredContent": None})()
+ )
+ session_cls.return_value.__aenter__ = mock.AsyncMock(return_value=session)
+ session_cls.return_value.__aexit__ = mock.AsyncMock(return_value=False)
+ _run(_Integration().call_tool("noop", {}))
+
+ def test_open_session_uses_headers_signature(self):
+ # streamablehttp_client(url, headers=...)
+ captured = {}
+
+ class _CM:
+ async def __aenter__(self_inner):
+ return ("read", "write", None)
+
+ async def __aexit__(self_inner, *a):
+ return False
+
+ def transport(url, headers=None):
+ captured["headers"] = headers
+ return _CM()
+
+ self._run_open_session_with_transport(transport)
+ self.assertEqual(captured["headers"], {"Authorization": "Bearer tok-xyz"})
+
+ def test_open_session_uses_http_client_signature(self):
+ # streamable_http_client(url, *, http_client=...) — must NOT pass headers=
+ captured = {}
+
+ class _CM:
+ async def __aenter__(self_inner):
+ return ("read", "write", None)
+
+ async def __aexit__(self_inner, *a):
+ return False
+
+ def transport(url, *, http_client=None):
+ captured["http_client"] = http_client
+ return _CM()
+
+ self._run_open_session_with_transport(transport)
+ self.assertIsNotNone(captured["http_client"])
+
+ def test_resolve_config_prefers_host_override_and_headers(self):
+ async def host_with_override(req_type, payload):
+ return {"url": "https://override.test/mcp", "headers": {"X-Extra": "1"}}
+
+ async def host_empty(req_type, payload):
+ return {}
+
+ with mock.patch.object(mcp_base, "host_request", host_with_override):
+ url, headers = _run(_Integration()._resolve_config())
+ self.assertEqual(url, "https://override.test/mcp")
+ self.assertEqual(headers, {"X-Extra": "1"})
+ with mock.patch.object(mcp_base, "host_request", host_empty):
+ url, headers = _run(_Integration()._resolve_config())
+ self.assertEqual(url, _Integration.url)
+ self.assertEqual(headers, {})
+
+
+if __name__ == "__main__":
+ unittest.main()