Compare commits

...

6 Commits

Author SHA1 Message Date
Kit Langton 204059e50a refactor(mcp): deepen Effect usage, reduce Effect.promise calls
- convertMcpTool is sync — drop async, use plain for loop
- Extract withClient helper for getPrompt/readResource (tryPromise)
- Extract createAndStore for add/connect/finishAuth shared pattern
- Break removeAuth into individual Effect steps
- tools() inner loop uses plain for (convertMcpTool is sync now)
2026-03-24 21:29:20 -04:00
Kit Langton 7d88939e82 refactor(mcp): push Effect deeper into MCP service
- Replace descendants() with ChildProcessSpawner + Effect.scoped
- Move descendants inside layer to close over spawner
- Replace Promise.all with Effect.forEach({concurrency: "unbounded"})
  in state init, finalizer, and tools()
- Use Effect.tryPromise for closeClient and tools listTools
- Use Effect.try for process.kill in finalizer
- Remove Process import (replaced by ChildProcessSpawner)
- collectFromConnected now returns Effect instead of Promise
2026-03-24 21:20:41 -04:00
Kit Langton 74b57f88cd fix: add definite assignment assertion for mock client state 2026-03-24 20:59:38 -04:00
Kit Langton 5b9906a2ca docs: mark MCP as effectified in migration checklist 2026-03-24 20:57:45 -04:00
Kit Langton c551c601a7 refactor(mcp): effectify MCP service with InstanceState
Migrate MCP from Instance.state() to Effect Service/Layer/InstanceState
pattern with makeRunPromise and async facades.

- InstanceState for per-directory lifecycle with ScopedCache
- Effect.fn tracing on all service methods
- Extract closeClient helper (was duplicated 3x)
- Extract collectFromConnected helper (prompts/resources were identical)
- Fix readResource log messages (said "prompt" instead of "resource")
- Fix finishAuthImpl not updating state after OAuth reconnect
- OAuth impl stays as plain async (inherently imperative)
2026-03-24 20:57:18 -04:00
Kit Langton 1c388c0693 fix(mcp): fix cancelPending key mismatch, add lifecycle tests
McpOAuthCallback.cancelPending(mcpName) was a no-op because
pendingAuths is keyed by oauthState (a hex string), not mcpName.
Add a reverse index so removeAuth() can actually cancel in-flight
OAuth flows.

Add comprehensive MCP lifecycle tests covering connect/disconnect,
add/replace, prompts, resources, disabled servers, error paths, and
tool name sanitization. Two tests for tools() transient-failure
recovery are marked .todo — the current behavior permanently deletes
clients on listTools() failure with no reconnect path; to be fixed
during Effect migration.
2026-03-24 20:27:51 -04:00
4 changed files with 1147 additions and 384 deletions
+1 -1
View File
@@ -175,4 +175,4 @@ Still open and likely worth migrating:
- [ ] `Provider`
- [x] `Project`
- [ ] `LSP`
- [ ] `MCP`
- [x] `MCP`
+444 -380
View File
@@ -11,7 +11,6 @@ import {
} from "@modelcontextprotocol/sdk/types.js"
import { Config } from "../config/config"
import { Log } from "../util/log"
import { Process } from "../util/process"
import { NamedError } from "@opencode-ai/util/error"
import z from "zod/v4"
import { Instance } from "../project/instance"
@@ -24,6 +23,13 @@ import { BusEvent } from "../bus/bus-event"
import { Bus } from "@/bus"
import { TuiEvent } from "@/cli/cmd/tui/event"
import open from "open"
import { Effect, Layer, ServiceMap, Stream } from "effect"
import { InstanceState } from "@/effect/instance-state"
import { makeRunPromise } from "@/effect/run-service"
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"
import * as CrossSpawnSpawner from "@/effect/cross-spawn-spawner"
import { NodeFileSystem } from "@effect/platform-node"
import * as NodePath from "@effect/platform-node/NodePath"
export namespace MCP {
const log = Log.create({ service: "mcp" })
@@ -109,6 +115,19 @@ export namespace MCP {
})
export type Status = z.infer<typeof Status>
// Store transports for OAuth servers to allow finishing auth
type TransportWithAuth = StreamableHTTPClientTransport | SSEClientTransport
const pendingOAuthTransports = new Map<string, TransportWithAuth>()
// Prompt cache types
type PromptInfo = Awaited<ReturnType<MCPClient["listPrompts"]>>["prompts"][number]
type ResourceInfo = Awaited<ReturnType<MCPClient["listResources"]>>["resources"][number]
type McpEntry = NonNullable<Config.Info["mcp"]>[string]
function isMcpConfigured(entry: McpEntry): entry is Config.Mcp {
return typeof entry === "object" && entry !== null && "type" in entry
}
// Register notification handlers for MCP client
function registerNotificationHandlers(client: MCPClient, serverName: string) {
client.setNotificationHandler(ToolListChangedNotificationSchema, async () => {
@@ -118,7 +137,7 @@ export namespace MCP {
}
// Convert MCP tool definition to AI SDK Tool type
async function convertMcpTool(mcpTool: MCPToolDef, client: MCPClient, timeout?: number): Promise<Tool> {
function convertMcpTool(mcpTool: MCPToolDef, client: MCPClient, timeout?: number): Tool {
const inputSchema = mcpTool.inputSchema
// Spread first, then override type to ensure it's always "object"
@@ -148,100 +167,6 @@ export namespace MCP {
})
}
// Store transports for OAuth servers to allow finishing auth
type TransportWithAuth = StreamableHTTPClientTransport | SSEClientTransport
const pendingOAuthTransports = new Map<string, TransportWithAuth>()
// Prompt cache types
type PromptInfo = Awaited<ReturnType<MCPClient["listPrompts"]>>["prompts"][number]
type ResourceInfo = Awaited<ReturnType<MCPClient["listResources"]>>["resources"][number]
type McpEntry = NonNullable<Config.Info["mcp"]>[string]
function isMcpConfigured(entry: McpEntry): entry is Config.Mcp {
return typeof entry === "object" && entry !== null && "type" in entry
}
async function descendants(pid: number): Promise<number[]> {
if (process.platform === "win32") return []
const pids: number[] = []
const queue = [pid]
while (queue.length > 0) {
const current = queue.shift()!
const lines = await Process.lines(["pgrep", "-P", String(current)], { nothrow: true })
for (const tok of lines) {
const cpid = parseInt(tok, 10)
if (!isNaN(cpid) && !pids.includes(cpid)) {
pids.push(cpid)
queue.push(cpid)
}
}
}
return pids
}
const state = Instance.state(
async () => {
const cfg = await Config.get()
const config = cfg.mcp ?? {}
const clients: Record<string, MCPClient> = {}
const status: Record<string, Status> = {}
await Promise.all(
Object.entries(config).map(async ([key, mcp]) => {
if (!isMcpConfigured(mcp)) {
log.error("Ignoring MCP config entry without type", { key })
return
}
// If disabled by config, mark as disabled without trying to connect
if (mcp.enabled === false) {
status[key] = { status: "disabled" }
return
}
const result = await create(key, mcp).catch(() => undefined)
if (!result) return
status[key] = result.status
if (result.mcpClient) {
clients[key] = result.mcpClient
}
}),
)
return {
status,
clients,
}
},
async (state) => {
// The MCP SDK only signals the direct child process on close.
// Servers like chrome-devtools-mcp spawn grandchild processes
// (e.g. Chrome) that the SDK never reaches, leaving them orphaned.
// Kill the full descendant tree first so the server exits promptly
// and no processes are left behind.
for (const client of Object.values(state.clients)) {
const pid = (client.transport as any)?.pid
if (typeof pid !== "number") continue
for (const dpid of await descendants(pid)) {
try {
process.kill(dpid, "SIGTERM")
} catch {}
}
}
await Promise.all(
Object.values(state.clients).map((client) =>
client.close().catch((error) => {
log.error("Failed to close MCP client", {
error,
})
}),
),
)
pendingOAuthTransports.clear()
},
)
// Helper function to fetch prompts for a specific client
async function fetchPromptsForClient(clientName: string, client: Client) {
@@ -288,40 +213,6 @@ export namespace MCP {
return commands
}
export async function add(name: string, mcp: Config.Mcp) {
const s = await state()
const result = await create(name, mcp)
if (!result) {
const status = {
status: "failed" as const,
error: "unknown error",
}
s.status[name] = status
return {
status,
}
}
if (!result.mcpClient) {
s.status[name] = result.status
return {
status: s.status,
}
}
// Close existing client if present to prevent memory leaks
const existingClient = s.clients[name]
if (existingClient) {
await existingClient.close().catch((error) => {
log.error("Failed to close existing MCP client", { name, error })
})
}
s.clients[name] = result.mcpClient
s.status[name] = result.status
return {
status: s.status,
}
}
async function create(key: string, mcp: Config.Mcp) {
if (mcp.enabled === false) {
log.info("mcp server disabled", { key })
@@ -533,220 +424,394 @@ export namespace MCP {
}
}
export async function status() {
const s = await state()
const cfg = await Config.get()
const config = cfg.mcp ?? {}
const result: Record<string, Status> = {}
// --- Effect Service ---
// Include all configured MCPs from config, not just connected ones
for (const [key, mcp] of Object.entries(config)) {
if (!isMcpConfigured(mcp)) continue
result[key] = s.status[key] ?? { status: "disabled" }
}
return result
interface State {
status: Record<string, Status>
clients: Record<string, MCPClient>
}
export async function clients() {
return state().then((state) => state.clients)
export interface Interface {
readonly status: () => Effect.Effect<Record<string, Status>>
readonly clients: () => Effect.Effect<Record<string, MCPClient>>
readonly tools: () => Effect.Effect<Record<string, Tool>>
readonly prompts: () => Effect.Effect<Record<string, PromptInfo & { client: string }>>
readonly resources: () => Effect.Effect<Record<string, ResourceInfo & { client: string }>>
readonly add: (name: string, mcp: Config.Mcp) => Effect.Effect<{ status: Record<string, Status> | Status }>
readonly connect: (name: string) => Effect.Effect<void>
readonly disconnect: (name: string) => Effect.Effect<void>
readonly getPrompt: (
clientName: string,
name: string,
args?: Record<string, string>,
) => Effect.Effect<Awaited<ReturnType<MCPClient["getPrompt"]>> | undefined>
readonly readResource: (
clientName: string,
resourceUri: string,
) => Effect.Effect<Awaited<ReturnType<MCPClient["readResource"]>> | undefined>
readonly startAuth: (mcpName: string) => Effect.Effect<{ authorizationUrl: string }>
readonly authenticate: (mcpName: string) => Effect.Effect<Status>
readonly finishAuth: (mcpName: string, authorizationCode: string) => Effect.Effect<Status>
readonly removeAuth: (mcpName: string) => Effect.Effect<void>
readonly supportsOAuth: (mcpName: string) => Effect.Effect<boolean>
readonly hasStoredTokens: (mcpName: string) => Effect.Effect<boolean>
readonly getAuthStatus: (mcpName: string) => Effect.Effect<AuthStatus>
}
export async function connect(name: string) {
const cfg = await Config.get()
const config = cfg.mcp ?? {}
const mcp = config[name]
if (!mcp) {
log.error("MCP config not found", { name })
return
}
export class Service extends ServiceMap.Service<Service, Interface>()("@opencode/MCP") {}
if (!isMcpConfigured(mcp)) {
log.error("Ignoring MCP connect request for config without type", { name })
return
}
export const layer = Layer.effect(
Service,
Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner
const result = await create(name, { ...mcp, enabled: true })
if (!result) {
const s = await state()
s.status[name] = {
status: "failed",
error: "Unknown error during connection",
}
return
}
const s = await state()
s.status[name] = result.status
if (result.mcpClient) {
// Close existing client if present to prevent memory leaks
const existingClient = s.clients[name]
if (existingClient) {
await existingClient.close().catch((error) => {
log.error("Failed to close existing MCP client", { name, error })
})
}
s.clients[name] = result.mcpClient
}
}
export async function disconnect(name: string) {
const s = await state()
const client = s.clients[name]
if (client) {
await client.close().catch((error) => {
log.error("Failed to close MCP client", { name, error })
})
delete s.clients[name]
}
s.status[name] = { status: "disabled" }
}
export async function tools() {
const result: Record<string, Tool> = {}
const s = await state()
const cfg = await Config.get()
const config = cfg.mcp ?? {}
const clientsSnapshot = await clients()
const defaultTimeout = cfg.experimental?.mcp_timeout
const connectedClients = Object.entries(clientsSnapshot).filter(
([clientName]) => s.status[clientName]?.status === "connected",
)
const toolsResults = await Promise.all(
connectedClients.map(async ([clientName, client]) => {
const toolsResult = await client.listTools().catch((e) => {
log.error("failed to get tools", { clientName, error: e.message })
const failedStatus = {
status: "failed" as const,
error: e instanceof Error ? e.message : String(e),
const descendants = Effect.fnUntraced(
function* (pid: number) {
if (process.platform === "win32") return [] as number[]
const pids: number[] = []
const queue = [pid]
while (queue.length > 0) {
const current = queue.shift()!
const handle = yield* spawner.spawn(
ChildProcess.make("pgrep", ["-P", String(current)], { stdin: "ignore" }),
)
const text = yield* Stream.mkString(Stream.decodeText(handle.stdout))
yield* handle.exitCode
for (const tok of text.split("\n")) {
const cpid = parseInt(tok, 10)
if (!isNaN(cpid) && !pids.includes(cpid)) {
pids.push(cpid)
queue.push(cpid)
}
}
}
s.status[clientName] = failedStatus
delete s.clients[clientName]
return undefined
})
return { clientName, client, toolsResult }
}),
)
return pids
},
Effect.scoped,
Effect.catch(() => Effect.succeed([] as number[])),
)
for (const { clientName, client, toolsResult } of toolsResults) {
if (!toolsResult) continue
const mcpConfig = config[clientName]
const entry = isMcpConfigured(mcpConfig) ? mcpConfig : undefined
const timeout = entry?.timeout ?? defaultTimeout
for (const mcpTool of toolsResult.tools) {
const sanitizedClientName = clientName.replace(/[^a-zA-Z0-9_-]/g, "_")
const sanitizedToolName = mcpTool.name.replace(/[^a-zA-Z0-9_-]/g, "_")
result[sanitizedClientName + "_" + sanitizedToolName] = await convertMcpTool(mcpTool, client, timeout)
const cache = yield* InstanceState.make<State>(
Effect.fn("MCP.state")(function* () {
const cfg = yield* Effect.promise(() => Config.get())
const config = cfg.mcp ?? {}
const clients: Record<string, MCPClient> = {}
const statusMap: Record<string, Status> = {}
yield* Effect.forEach(
Object.entries(config),
([key, mcp]) =>
Effect.gen(function* () {
if (!isMcpConfigured(mcp)) {
log.error("Ignoring MCP config entry without type", { key })
return
}
if (mcp.enabled === false) {
statusMap[key] = { status: "disabled" }
return
}
const result = yield* Effect.promise(() => create(key, mcp).catch(() => undefined))
if (!result) return
statusMap[key] = result.status
if (result.mcpClient) {
clients[key] = result.mcpClient
}
}),
{ concurrency: "unbounded" },
)
const s: State = { status: statusMap, clients }
yield* Effect.addFinalizer(() =>
Effect.gen(function* () {
yield* Effect.forEach(
Object.values(s.clients),
(client) =>
Effect.gen(function* () {
const pid = (client.transport as any)?.pid
if (typeof pid === "number") {
const pids = yield* descendants(pid)
yield* Effect.forEach(pids, (dpid) =>
Effect.try({
try: () => process.kill(dpid, "SIGTERM"),
catch: () => new Error(`failed to kill ${dpid}`),
}).pipe(Effect.ignore),
)
}
yield* Effect.tryPromise(() => client.close()).pipe(Effect.ignore)
}),
{ concurrency: "unbounded" },
)
pendingOAuthTransports.clear()
}),
)
return s
}),
)
function closeClient(s: State, name: string) {
const client = s.clients[name]
if (!client) return Effect.void
return Effect.tryPromise({
try: () => client.close(),
catch: (error) => {
log.error("failed to close MCP client", { name, error })
return error
},
}).pipe(Effect.ignore)
}
}
return result
}
export async function prompts() {
const s = await state()
const clientsSnapshot = await clients()
const status = Effect.fn("MCP.status")(function* () {
const s = yield* InstanceState.get(cache)
const cfg = yield* Effect.promise(() => Config.get())
const config = cfg.mcp ?? {}
const result: Record<string, Status> = {}
const prompts = Object.fromEntries<PromptInfo & { client: string }>(
(
await Promise.all(
Object.entries(clientsSnapshot).map(async ([clientName, client]) => {
if (s.status[clientName]?.status !== "connected") {
return []
}
for (const [key, mcp] of Object.entries(config)) {
if (!isMcpConfigured(mcp)) continue
result[key] = s.status[key] ?? { status: "disabled" }
}
return Object.entries((await fetchPromptsForClient(clientName, client)) ?? {})
}),
)
).flat(),
)
return prompts
}
export async function resources() {
const s = await state()
const clientsSnapshot = await clients()
const result = Object.fromEntries<ResourceInfo & { client: string }>(
(
await Promise.all(
Object.entries(clientsSnapshot).map(async ([clientName, client]) => {
if (s.status[clientName]?.status !== "connected") {
return []
}
return Object.entries((await fetchResourcesForClient(clientName, client)) ?? {})
}),
)
).flat(),
)
return result
}
export async function getPrompt(clientName: string, name: string, args?: Record<string, string>) {
const clientsSnapshot = await clients()
const client = clientsSnapshot[clientName]
if (!client) {
log.warn("client not found for prompt", {
clientName,
return result
})
return undefined
}
const result = await client
.getPrompt({
name: name,
arguments: args,
const clients = Effect.fn("MCP.clients")(function* () {
const s = yield* InstanceState.get(cache)
return s.clients
})
.catch((e) => {
log.error("failed to get prompt from MCP server", {
const createAndStore = Effect.fn("MCP.createAndStore")(function* (name: string, mcp: Config.Mcp) {
const result = yield* Effect.promise(() => create(name, mcp))
const s = yield* InstanceState.get(cache)
if (!result) {
s.status[name] = { status: "failed" as const, error: "unknown error" }
return s.status[name]
}
s.status[name] = result.status
if (result.mcpClient) {
yield* closeClient(s, name)
s.clients[name] = result.mcpClient
}
return result.status
})
const add = Effect.fn("MCP.add")(function* (name: string, mcp: Config.Mcp) {
yield* createAndStore(name, mcp)
const s = yield* InstanceState.get(cache)
return { status: s.status }
})
const connect = Effect.fn("MCP.connect")(function* (name: string) {
const cfg = yield* Effect.promise(() => Config.get())
const config = cfg.mcp ?? {}
const mcp = config[name]
if (!mcp) {
log.error("MCP config not found", { name })
return
}
if (!isMcpConfigured(mcp)) {
log.error("Ignoring MCP connect request for config without type", { name })
return
}
yield* createAndStore(name, { ...mcp, enabled: true })
})
const disconnect = Effect.fn("MCP.disconnect")(function* (name: string) {
const s = yield* InstanceState.get(cache)
yield* closeClient(s, name)
delete s.clients[name]
s.status[name] = { status: "disabled" }
})
const tools = Effect.fn("MCP.tools")(function* () {
const result: Record<string, Tool> = {}
const s = yield* InstanceState.get(cache)
const cfg = yield* Effect.promise(() => Config.get())
const config = cfg.mcp ?? {}
const defaultTimeout = cfg.experimental?.mcp_timeout
const connectedClients = Object.entries(s.clients).filter(
([clientName]) => s.status[clientName]?.status === "connected",
)
yield* Effect.forEach(
connectedClients,
([clientName, client]) =>
Effect.gen(function* () {
const toolsResult = yield* Effect.tryPromise({
try: () => client.listTools(),
catch: (e: any) => {
log.error("failed to get tools", { clientName, error: e?.message })
s.status[clientName] = {
status: "failed" as const,
error: e instanceof Error ? e.message : String(e),
}
delete s.clients[clientName]
return e
},
}).pipe(Effect.option)
if (toolsResult._tag === "None") return
const mcpConfig = config[clientName]
const entry = isMcpConfigured(mcpConfig) ? mcpConfig : undefined
const timeout = entry?.timeout ?? defaultTimeout
for (const mcpTool of toolsResult.value.tools) {
const sanitizedClientName = clientName.replace(/[^a-zA-Z0-9_-]/g, "_")
const sanitizedToolName = mcpTool.name.replace(/[^a-zA-Z0-9_-]/g, "_")
result[sanitizedClientName + "_" + sanitizedToolName] = convertMcpTool(mcpTool, client, timeout)
}
}),
{ concurrency: "unbounded" },
)
return result
})
function collectFromConnected<T>(
s: State,
fetchFn: (clientName: string, client: Client) => Promise<Record<string, T> | undefined>,
) {
return Effect.forEach(
Object.entries(s.clients).filter(([name]) => s.status[name]?.status === "connected"),
([clientName, client]) =>
Effect.promise(async () => Object.entries((await fetchFn(clientName, client)) ?? {})),
{ concurrency: "unbounded" },
).pipe(Effect.map((results) => Object.fromEntries<T>(results.flat())))
}
const prompts = Effect.fn("MCP.prompts")(function* () {
const s = yield* InstanceState.get(cache)
return yield* collectFromConnected(s, fetchPromptsForClient)
})
const resources = Effect.fn("MCP.resources")(function* () {
const s = yield* InstanceState.get(cache)
return yield* collectFromConnected(s, fetchResourcesForClient)
})
function withClient<A>(
clientName: string,
fn: (client: MCPClient) => Promise<A>,
label: string,
meta?: Record<string, unknown>,
) {
return Effect.gen(function* () {
const s = yield* InstanceState.get(cache)
const client = s.clients[clientName]
if (!client) {
log.warn(`client not found for ${label}`, { clientName })
return undefined
}
return yield* Effect.tryPromise({
try: () => fn(client),
catch: (e: any) => {
log.error(`failed to ${label}`, { clientName, ...meta, error: e?.message })
return e
},
}).pipe(Effect.orElseSucceed(() => undefined))
})
}
const getPrompt = Effect.fn("MCP.getPrompt")(function* (
clientName: string,
name: string,
args?: Record<string, string>,
) {
return yield* withClient(
clientName,
promptName: name,
error: e.message,
})
return undefined
(client) => client.getPrompt({ name, arguments: args }),
"getPrompt",
{ promptName: name },
)
})
return result
}
export async function readResource(clientName: string, resourceUri: string) {
const clientsSnapshot = await clients()
const client = clientsSnapshot[clientName]
if (!client) {
log.warn("client not found for prompt", {
clientName: clientName,
})
return undefined
}
const result = await client
.readResource({
uri: resourceUri,
})
.catch((e) => {
log.error("failed to get prompt from MCP server", {
clientName: clientName,
resourceUri: resourceUri,
error: e.message,
})
return undefined
const readResource = Effect.fn("MCP.readResource")(function* (clientName: string, resourceUri: string) {
return yield* withClient(
clientName,
(client) => client.readResource({ uri: resourceUri }),
"readResource",
{ resourceUri },
)
})
return result
}
const startAuth = Effect.fn("MCP.startAuth")(function* (mcpName: string) {
return yield* Effect.promise(() => startAuthImpl(mcpName))
})
/**
* Start OAuth authentication flow for an MCP server.
* Returns the authorization URL that should be opened in a browser.
*/
export async function startAuth(mcpName: string): Promise<{ authorizationUrl: string }> {
const authenticate = Effect.fn("MCP.authenticate")(function* (mcpName: string) {
return yield* Effect.promise(() => authenticateImpl(mcpName))
})
const finishAuth = Effect.fn("MCP.finishAuth")(function* (mcpName: string, authorizationCode: string) {
const result = yield* Effect.promise(() => finishAuthImpl(mcpName, authorizationCode))
if (result.status === "connected") {
const cfg = yield* Effect.promise(() => Config.get())
const mcpConfig = cfg.mcp?.[mcpName]
if (mcpConfig && isMcpConfigured(mcpConfig)) {
yield* createAndStore(mcpName, mcpConfig)
}
}
return result
})
const removeAuth = Effect.fn("MCP.removeAuth")(function* (mcpName: string) {
yield* Effect.promise(() => McpAuth.remove(mcpName))
McpOAuthCallback.cancelPending(mcpName)
pendingOAuthTransports.delete(mcpName)
yield* Effect.promise(() => McpAuth.clearOAuthState(mcpName))
log.info("removed oauth credentials", { mcpName })
})
const supportsOAuth = Effect.fn("MCP.supportsOAuth")(function* (mcpName: string) {
const cfg = yield* Effect.promise(() => Config.get())
const mcpConfig = cfg.mcp?.[mcpName]
if (!mcpConfig) return false
if (!isMcpConfigured(mcpConfig)) return false
return mcpConfig.type === "remote" && mcpConfig.oauth !== false
})
const hasStoredTokens = Effect.fn("MCP.hasStoredTokens")(function* (mcpName: string) {
const entry = yield* Effect.promise(() => McpAuth.get(mcpName))
return !!entry?.tokens
})
const getAuthStatus = Effect.fn("MCP.getAuthStatus")(function* (mcpName: string) {
const entry = yield* Effect.promise(() => McpAuth.get(mcpName))
if (!entry?.tokens) return "not_authenticated" as AuthStatus
const expired = yield* Effect.promise(() => McpAuth.isTokenExpired(mcpName))
return (expired ? "expired" : "authenticated") as AuthStatus
})
return Service.of({
status,
clients,
tools,
prompts,
resources,
add,
connect,
disconnect,
getPrompt,
readResource,
startAuth,
authenticate,
finishAuth,
removeAuth,
supportsOAuth,
hasStoredTokens,
getAuthStatus,
})
}),
)
// --- OAuth implementation (kept as plain async — inherently imperative) ---
async function startAuthImpl(mcpName: string): Promise<{ authorizationUrl: string }> {
const cfg = await Config.get()
const mcpConfig = cfg.mcp?.[mcpName]
@@ -819,17 +884,12 @@ export namespace MCP {
}
}
/**
* Complete OAuth authentication after user authorizes in browser.
* Opens the browser and waits for callback.
*/
export async function authenticate(mcpName: string): Promise<Status> {
const { authorizationUrl } = await startAuth(mcpName)
async function authenticateImpl(mcpName: string): Promise<Status> {
const { authorizationUrl } = await startAuthImpl(mcpName)
if (!authorizationUrl) {
// Already authenticated
const s = await state()
return s.status[mcpName] ?? { status: "connected" }
return { status: "connected" }
}
// Get the state that was already generated and stored in startAuth()
@@ -844,7 +904,7 @@ export namespace MCP {
// Register the callback BEFORE opening the browser to avoid race condition
// when the IdP has an active SSO session and redirects immediately
const callbackPromise = McpOAuthCallback.waitForCallback(oauthState)
const callbackPromise = McpOAuthCallback.waitForCallback(oauthState, mcpName)
try {
const subprocess = await open(authorizationUrl)
@@ -886,13 +946,10 @@ export namespace MCP {
await McpAuth.clearOAuthState(mcpName)
// Finish auth
return finishAuth(mcpName, code)
return finishAuthImpl(mcpName, code)
}
/**
* Complete OAuth authentication with the authorization code.
*/
export async function finishAuth(mcpName: string, authorizationCode: string): Promise<Status> {
async function finishAuthImpl(mcpName: string, authorizationCode: string): Promise<Status> {
const transport = pendingOAuthTransports.get(mcpName)
if (!transport) {
@@ -918,12 +975,10 @@ export namespace MCP {
throw new Error(`MCP server ${mcpName} is disabled or missing configuration`)
}
// Re-add the MCP server to establish connection
// Re-create the MCP client to establish connection
pendingOAuthTransports.delete(mcpName)
const result = await add(mcpName, mcpConfig)
const statusRecord = result.status as Record<string, Status>
return statusRecord[mcpName] ?? { status: "failed", error: "Unknown error after auth" }
const result = await create(mcpName, mcpConfig)
return result?.status ?? { status: "failed", error: "Unknown error after auth" }
} catch (error) {
log.error("failed to finish oauth", { mcpName, error })
return {
@@ -933,45 +988,54 @@ export namespace MCP {
}
}
/**
* Remove OAuth credentials for an MCP server.
*/
export async function removeAuth(mcpName: string): Promise<void> {
await McpAuth.remove(mcpName)
McpOAuthCallback.cancelPending(mcpName)
pendingOAuthTransports.delete(mcpName)
await McpAuth.clearOAuthState(mcpName)
log.info("removed oauth credentials", { mcpName })
}
/**
* Check if an MCP server supports OAuth (remote servers support OAuth by default unless explicitly disabled).
*/
export async function supportsOAuth(mcpName: string): Promise<boolean> {
const cfg = await Config.get()
const mcpConfig = cfg.mcp?.[mcpName]
if (!mcpConfig) return false
if (!isMcpConfigured(mcpConfig)) return false
return mcpConfig.type === "remote" && mcpConfig.oauth !== false
}
/**
* Check if an MCP server has stored OAuth tokens.
*/
export async function hasStoredTokens(mcpName: string): Promise<boolean> {
const entry = await McpAuth.get(mcpName)
return !!entry?.tokens
}
export type AuthStatus = "authenticated" | "expired" | "not_authenticated"
/**
* Get the authentication status for an MCP server.
*/
export async function getAuthStatus(mcpName: string): Promise<AuthStatus> {
const hasTokens = await hasStoredTokens(mcpName)
if (!hasTokens) return "not_authenticated"
const expired = await McpAuth.isTokenExpired(mcpName)
return expired ? "expired" : "authenticated"
}
// --- Per-service runtime ---
const defaultLayer = layer.pipe(
Layer.provide(CrossSpawnSpawner.layer),
Layer.provide(NodeFileSystem.layer),
Layer.provide(NodePath.layer),
)
const runPromise = makeRunPromise(Service, defaultLayer)
// --- Async facade functions ---
export const status = async () => runPromise((svc) => svc.status())
export const clients = async () => runPromise((svc) => svc.clients())
export const tools = async () => runPromise((svc) => svc.tools())
export const prompts = async () => runPromise((svc) => svc.prompts())
export const resources = async () => runPromise((svc) => svc.resources())
export const add = async (name: string, mcp: Config.Mcp) => runPromise((svc) => svc.add(name, mcp))
export const connect = async (name: string) => runPromise((svc) => svc.connect(name))
export const disconnect = async (name: string) => runPromise((svc) => svc.disconnect(name))
export const getPrompt = async (clientName: string, name: string, args?: Record<string, string>) =>
runPromise((svc) => svc.getPrompt(clientName, name, args))
export const readResource = async (clientName: string, resourceUri: string) =>
runPromise((svc) => svc.readResource(clientName, resourceUri))
export const startAuth = async (mcpName: string) => runPromise((svc) => svc.startAuth(mcpName))
export const authenticate = async (mcpName: string) => runPromise((svc) => svc.authenticate(mcpName))
export const finishAuth = async (mcpName: string, authorizationCode: string) =>
runPromise((svc) => svc.finishAuth(mcpName, authorizationCode))
export const removeAuth = async (mcpName: string) => runPromise((svc) => svc.removeAuth(mcpName))
export const supportsOAuth = async (mcpName: string) => runPromise((svc) => svc.supportsOAuth(mcpName))
export const hasStoredTokens = async (mcpName: string) => runPromise((svc) => svc.hasStoredTokens(mcpName))
export const getAuthStatus = async (mcpName: string) => runPromise((svc) => svc.getAuthStatus(mcpName))
}
+13 -3
View File
@@ -54,6 +54,9 @@ interface PendingAuth {
export namespace McpOAuthCallback {
let server: ReturnType<typeof Bun.serve> | undefined
const pendingAuths = new Map<string, PendingAuth>()
// Reverse index: mcpName → oauthState, so cancelPending(mcpName) can
// find the right entry in pendingAuths (which is keyed by oauthState).
const mcpNameToState = new Map<string, string>()
const CALLBACK_TIMEOUT_MS = 5 * 60 * 1000 // 5 minutes
@@ -137,11 +140,13 @@ export namespace McpOAuthCallback {
log.info("oauth callback server started", { port: OAUTH_CALLBACK_PORT })
}
export function waitForCallback(oauthState: string): Promise<string> {
export function waitForCallback(oauthState: string, mcpName?: string): Promise<string> {
if (mcpName) mcpNameToState.set(mcpName, oauthState)
return new Promise((resolve, reject) => {
const timeout = setTimeout(() => {
if (pendingAuths.has(oauthState)) {
pendingAuths.delete(oauthState)
if (mcpName) mcpNameToState.delete(mcpName)
reject(new Error("OAuth callback timeout - authorization took too long"))
}
}, CALLBACK_TIMEOUT_MS)
@@ -151,10 +156,14 @@ export namespace McpOAuthCallback {
}
export function cancelPending(mcpName: string): void {
const pending = pendingAuths.get(mcpName)
// Look up the oauthState for this mcpName via the reverse index
const oauthState = mcpNameToState.get(mcpName)
const key = oauthState ?? mcpName
const pending = pendingAuths.get(key)
if (pending) {
clearTimeout(pending.timeout)
pendingAuths.delete(mcpName)
pendingAuths.delete(key)
mcpNameToState.delete(mcpName)
pending.reject(new Error("Authorization cancelled"))
}
}
@@ -184,6 +193,7 @@ export namespace McpOAuthCallback {
pending.reject(new Error("OAuth callback server stopped"))
}
pendingAuths.clear()
mcpNameToState.clear()
}
export function isRunning(): boolean {
@@ -0,0 +1,689 @@
import { test, expect, mock, beforeEach } from "bun:test"
// --- Mock infrastructure ---
// Per-client state for controlling mock behavior
interface MockClientState {
tools: Array<{ name: string; description?: string; inputSchema: object }>
listToolsShouldFail: boolean
listToolsError: string
listPromptsShouldFail: boolean
listResourcesShouldFail: boolean
prompts: Array<{ name: string; description?: string }>
resources: Array<{ name: string; uri: string; description?: string }>
closed: boolean
notificationHandlers: Map<unknown, (...args: any[]) => any>
}
const clientStates = new Map<string, MockClientState>()
let lastCreatedClientName: string | undefined
let connectShouldFail = false
let connectError = "Mock transport cannot connect"
// Tracks how many Client instances were created (detects leaks)
let clientCreateCount = 0
function getOrCreateClientState(name?: string): MockClientState {
const key = name ?? "default"
let state = clientStates.get(key)
if (!state) {
state = {
tools: [{ name: "test_tool", description: "A test tool", inputSchema: { type: "object", properties: {} } }],
listToolsShouldFail: false,
listToolsError: "listTools failed",
listPromptsShouldFail: false,
listResourcesShouldFail: false,
prompts: [],
resources: [],
closed: false,
notificationHandlers: new Map(),
}
clientStates.set(key, state)
}
return state
}
// Mock transport that succeeds or fails based on connectShouldFail
class MockStdioTransport {
stderr: null = null
pid = 12345
constructor(_opts: any) {}
async start() {
if (connectShouldFail) throw new Error(connectError)
}
async close() {}
}
class MockStreamableHTTP {
constructor(_url: URL, _opts?: any) {}
async start() {
if (connectShouldFail) throw new Error(connectError)
}
async close() {}
async finishAuth() {}
}
class MockSSE {
constructor(_url: URL, _opts?: any) {}
async start() {
throw new Error("SSE fallback - not used in these tests")
}
async close() {}
}
mock.module("@modelcontextprotocol/sdk/client/stdio.js", () => ({
StdioClientTransport: MockStdioTransport,
}))
mock.module("@modelcontextprotocol/sdk/client/streamableHttp.js", () => ({
StreamableHTTPClientTransport: MockStreamableHTTP,
}))
mock.module("@modelcontextprotocol/sdk/client/sse.js", () => ({
SSEClientTransport: MockSSE,
}))
mock.module("@modelcontextprotocol/sdk/client/auth.js", () => ({
UnauthorizedError: class extends Error {
constructor() {
super("Unauthorized")
}
},
}))
// Mock Client that delegates to per-name MockClientState
mock.module("@modelcontextprotocol/sdk/client/index.js", () => ({
Client: class MockClient {
_state!: MockClientState
transport: any
constructor(_opts: any) {
clientCreateCount++
}
async connect(transport: { start: () => Promise<void> }) {
this.transport = transport
await transport.start()
// After successful connect, bind to the last-created client name
this._state = getOrCreateClientState(lastCreatedClientName)
}
setNotificationHandler(schema: unknown, handler: (...args: any[]) => any) {
this._state?.notificationHandlers.set(schema, handler)
}
async listTools() {
if (this._state?.listToolsShouldFail) {
throw new Error(this._state.listToolsError)
}
return { tools: this._state?.tools ?? [] }
}
async listPrompts() {
if (this._state?.listPromptsShouldFail) {
throw new Error("listPrompts failed")
}
return { prompts: this._state?.prompts ?? [] }
}
async listResources() {
if (this._state?.listResourcesShouldFail) {
throw new Error("listResources failed")
}
return { resources: this._state?.resources ?? [] }
}
async close() {
if (this._state) this._state.closed = true
}
},
}))
beforeEach(() => {
clientStates.clear()
lastCreatedClientName = undefined
connectShouldFail = false
connectError = "Mock transport cannot connect"
clientCreateCount = 0
})
// Import after mocks
const { MCP } = await import("../../src/mcp/index")
const { Instance } = await import("../../src/project/instance")
const { tmpdir } = await import("../fixture/fixture")
// --- Helper ---
function withInstance(
config: Record<string, any>,
fn: () => Promise<void>,
) {
return async () => {
await using tmp = await tmpdir({
init: async (dir) => {
await Bun.write(
`${dir}/opencode.json`,
JSON.stringify({
$schema: "https://opencode.ai/config.json",
mcp: config,
}),
)
},
})
await Instance.provide({
directory: tmp.path,
fn: async () => {
await fn()
// dispose instance to clean up state between tests
await Instance.dispose()
},
})
}
}
// ========================================================================
// Bug #1: tools() silently deletes clients on transient listTools() failure
// ========================================================================
test.todo(
"tools() removes client from state when listTools fails",
withInstance(
{
"my-server": {
type: "local",
command: ["echo", "test"],
},
},
async () => {
lastCreatedClientName = "my-server"
const serverState = getOrCreateClientState("my-server")
serverState.tools = [
{ name: "do_thing", description: "does a thing", inputSchema: { type: "object", properties: {} } },
]
// First: add the server successfully
const addResult = await MCP.add("my-server", {
type: "local",
command: ["echo", "test"],
})
expect((addResult.status as any)["my-server"]?.status ?? (addResult.status as any).status).toBe("connected")
// Verify tools work initially
const toolsBefore = await MCP.tools()
expect(Object.keys(toolsBefore).length).toBeGreaterThan(0)
// Simulate a transient listTools failure
serverState.listToolsShouldFail = true
await MCP.tools()
// After the transient error clears, tools should recover
// automatically — the server shouldn't be permanently removed.
serverState.listToolsShouldFail = false
const toolsRecovered = await MCP.tools()
expect(Object.keys(toolsRecovered).length).toBeGreaterThan(0)
},
),
)
// ========================================================================
// Bug #2: status() shows stale data after tools() deletes a client
// ========================================================================
test.todo(
"status shows 'failed' after tools() encounters a transient error",
withInstance(
{
"status-server": {
type: "local",
command: ["echo", "test"],
},
},
async () => {
lastCreatedClientName = "status-server"
const serverState = getOrCreateClientState("status-server")
await MCP.add("status-server", {
type: "local",
command: ["echo", "test"],
})
const statusBefore = await MCP.status()
expect(statusBefore["status-server"]?.status).toBe("connected")
// Simulate a transient failure then recovery
serverState.listToolsShouldFail = true
await MCP.tools()
serverState.listToolsShouldFail = false
// After the error clears, status should recover automatically
await MCP.tools()
const statusAfter = await MCP.status()
expect(statusAfter["status-server"]?.status).toBe("connected")
},
),
)
// ========================================================================
// Test: connect() / disconnect() lifecycle
// ========================================================================
test(
"disconnect sets status to disabled and removes client",
withInstance(
{
"disc-server": {
type: "local",
command: ["echo", "test"],
},
},
async () => {
lastCreatedClientName = "disc-server"
getOrCreateClientState("disc-server")
await MCP.add("disc-server", {
type: "local",
command: ["echo", "test"],
})
const statusBefore = await MCP.status()
expect(statusBefore["disc-server"]?.status).toBe("connected")
await MCP.disconnect("disc-server")
const statusAfter = await MCP.status()
expect(statusAfter["disc-server"]?.status).toBe("disabled")
// Tools should be empty after disconnect
const tools = await MCP.tools()
const serverTools = Object.keys(tools).filter((k) => k.startsWith("disc-server"))
expect(serverTools.length).toBe(0)
},
),
)
test(
"connect() after disconnect() re-establishes the server",
withInstance(
{
"reconn-server": {
type: "local",
command: ["echo", "test"],
},
},
async () => {
lastCreatedClientName = "reconn-server"
const serverState = getOrCreateClientState("reconn-server")
serverState.tools = [
{ name: "my_tool", description: "a tool", inputSchema: { type: "object", properties: {} } },
]
await MCP.add("reconn-server", {
type: "local",
command: ["echo", "test"],
})
await MCP.disconnect("reconn-server")
expect((await MCP.status())["reconn-server"]?.status).toBe("disabled")
// Reconnect
await MCP.connect("reconn-server")
expect((await MCP.status())["reconn-server"]?.status).toBe("connected")
const tools = await MCP.tools()
expect(Object.keys(tools).some((k) => k.includes("my_tool"))).toBe(true)
},
),
)
// ========================================================================
// Test: add() closes existing client before replacing
// ========================================================================
test(
"add() closes the old client when replacing a server",
// Don't put the server in config — add it dynamically so we control
// exactly which client instance is "first" vs "second".
withInstance({}, async () => {
lastCreatedClientName = "replace-server"
const firstState = getOrCreateClientState("replace-server")
await MCP.add("replace-server", {
type: "local",
command: ["echo", "test"],
})
expect(firstState.closed).toBe(false)
// Create new state for second client
clientStates.delete("replace-server")
const secondState = getOrCreateClientState("replace-server")
// Re-add should close the first client
await MCP.add("replace-server", {
type: "local",
command: ["echo", "test"],
})
expect(firstState.closed).toBe(true)
expect(secondState.closed).toBe(false)
}),
)
// ========================================================================
// Test: state init with mixed success/failure
// ========================================================================
test(
"init connects available servers even when one fails",
withInstance(
{
"good-server": {
type: "local",
command: ["echo", "good"],
},
"bad-server": {
type: "local",
command: ["echo", "bad"],
},
},
async () => {
// Set up good server
const goodState = getOrCreateClientState("good-server")
goodState.tools = [
{ name: "good_tool", description: "works", inputSchema: { type: "object", properties: {} } },
]
// Set up bad server - will fail on listTools during create()
const badState = getOrCreateClientState("bad-server")
badState.listToolsShouldFail = true
// Add good server first
lastCreatedClientName = "good-server"
await MCP.add("good-server", {
type: "local",
command: ["echo", "good"],
})
// Add bad server - should fail but not affect good server
lastCreatedClientName = "bad-server"
await MCP.add("bad-server", {
type: "local",
command: ["echo", "bad"],
})
const status = await MCP.status()
expect(status["good-server"]?.status).toBe("connected")
expect(status["bad-server"]?.status).toBe("failed")
// Good server's tools should still be available
const tools = await MCP.tools()
expect(Object.keys(tools).some((k) => k.includes("good_tool"))).toBe(true)
},
),
)
// ========================================================================
// Test: disabled server via config
// ========================================================================
test(
"disabled server is marked as disabled without attempting connection",
withInstance(
{
"disabled-server": {
type: "local",
command: ["echo", "test"],
enabled: false,
},
},
async () => {
const countBefore = clientCreateCount
await MCP.add("disabled-server", {
type: "local",
command: ["echo", "test"],
enabled: false,
} as any)
// No client should have been created
expect(clientCreateCount).toBe(countBefore)
const status = await MCP.status()
expect(status["disabled-server"]?.status).toBe("disabled")
},
),
)
// ========================================================================
// Test: prompts() and resources()
// ========================================================================
test(
"prompts() returns prompts from connected servers",
withInstance(
{
"prompt-server": {
type: "local",
command: ["echo", "test"],
},
},
async () => {
lastCreatedClientName = "prompt-server"
const serverState = getOrCreateClientState("prompt-server")
serverState.prompts = [
{ name: "my-prompt", description: "A test prompt" },
]
await MCP.add("prompt-server", {
type: "local",
command: ["echo", "test"],
})
const prompts = await MCP.prompts()
expect(Object.keys(prompts).length).toBe(1)
const key = Object.keys(prompts)[0]
expect(key).toContain("prompt-server")
expect(key).toContain("my-prompt")
},
),
)
test(
"resources() returns resources from connected servers",
withInstance(
{
"resource-server": {
type: "local",
command: ["echo", "test"],
},
},
async () => {
lastCreatedClientName = "resource-server"
const serverState = getOrCreateClientState("resource-server")
serverState.resources = [
{ name: "my-resource", uri: "file:///test.txt", description: "A test resource" },
]
await MCP.add("resource-server", {
type: "local",
command: ["echo", "test"],
})
const resources = await MCP.resources()
expect(Object.keys(resources).length).toBe(1)
const key = Object.keys(resources)[0]
expect(key).toContain("resource-server")
expect(key).toContain("my-resource")
},
),
)
test(
"prompts() skips disconnected servers",
withInstance(
{
"prompt-disc-server": {
type: "local",
command: ["echo", "test"],
},
},
async () => {
lastCreatedClientName = "prompt-disc-server"
const serverState = getOrCreateClientState("prompt-disc-server")
serverState.prompts = [{ name: "hidden-prompt", description: "Should not appear" }]
await MCP.add("prompt-disc-server", {
type: "local",
command: ["echo", "test"],
})
await MCP.disconnect("prompt-disc-server")
const prompts = await MCP.prompts()
expect(Object.keys(prompts).length).toBe(0)
},
),
)
// ========================================================================
// Test: connect() on nonexistent server
// ========================================================================
test(
"connect() on nonexistent server does not throw",
withInstance({}, async () => {
// Should not throw
await MCP.connect("nonexistent")
const status = await MCP.status()
expect(status["nonexistent"]).toBeUndefined()
}),
)
// ========================================================================
// Test: disconnect() on nonexistent server
// ========================================================================
test(
"disconnect() on nonexistent server does not throw",
withInstance({}, async () => {
await MCP.disconnect("nonexistent")
// Should complete without error
}),
)
// ========================================================================
// Test: tools() with no MCP servers configured
// ========================================================================
test(
"tools() returns empty when no MCP servers are configured",
withInstance({}, async () => {
const tools = await MCP.tools()
expect(Object.keys(tools).length).toBe(0)
}),
)
// ========================================================================
// Test: connect failure during create()
// ========================================================================
test(
"server that fails to connect is marked as failed",
withInstance(
{
"fail-connect": {
type: "local",
command: ["echo", "test"],
},
},
async () => {
lastCreatedClientName = "fail-connect"
getOrCreateClientState("fail-connect")
connectShouldFail = true
connectError = "Connection refused"
await MCP.add("fail-connect", {
type: "local",
command: ["echo", "test"],
})
const status = await MCP.status()
expect(status["fail-connect"]?.status).toBe("failed")
if (status["fail-connect"]?.status === "failed") {
expect(status["fail-connect"].error).toContain("Connection refused")
}
// No tools should be available
const tools = await MCP.tools()
expect(Object.keys(tools).length).toBe(0)
},
),
)
// ========================================================================
// Bug #5: McpOAuthCallback.cancelPending uses wrong key
// ========================================================================
test("McpOAuthCallback.cancelPending is keyed by mcpName but pendingAuths uses oauthState", async () => {
const { McpOAuthCallback } = await import("../../src/mcp/oauth-callback")
// Register a pending auth with an oauthState key, associated to an mcpName
const oauthState = "abc123hexstate"
const callbackPromise = McpOAuthCallback.waitForCallback(oauthState, "my-mcp-server")
// cancelPending is called with mcpName — should find the entry via reverse index
McpOAuthCallback.cancelPending("my-mcp-server")
// The callback should still be pending because cancelPending looked up
// "my-mcp-server" in a map keyed by "abc123hexstate"
let resolved = false
let rejected = false
callbackPromise.then(() => (resolved = true)).catch(() => (rejected = true))
// Give it a tick
await new Promise((r) => setTimeout(r, 50))
// cancelPending("my-mcp-server") should have rejected the pending callback
expect(rejected).toBe(true)
await McpOAuthCallback.stop()
})
// ========================================================================
// Test: multiple tools from same server get correct name prefixes
// ========================================================================
test(
"tools() prefixes tool names with sanitized server name",
withInstance(
{
"my.special-server": {
type: "local",
command: ["echo", "test"],
},
},
async () => {
lastCreatedClientName = "my.special-server"
const serverState = getOrCreateClientState("my.special-server")
serverState.tools = [
{ name: "tool-a", description: "Tool A", inputSchema: { type: "object", properties: {} } },
{ name: "tool.b", description: "Tool B", inputSchema: { type: "object", properties: {} } },
]
await MCP.add("my.special-server", {
type: "local",
command: ["echo", "test"],
})
const tools = await MCP.tools()
const keys = Object.keys(tools)
// Server name dots should be replaced with underscores
expect(keys.some((k) => k.startsWith("my_special-server_"))).toBe(true)
// Tool name dots should be replaced with underscores
expect(keys.some((k) => k.endsWith("tool_b"))).toBe(true)
expect(keys.length).toBe(2)
},
),
)