Skip to content

Commit b797751

Browse files
authored
refactor(mcp): simplify service helpers (#31549)
1 parent e49aa60 commit b797751

1 file changed

Lines changed: 28 additions & 48 deletions

File tree

‎packages/opencode/src/mcp/index.ts‎

Lines changed: 28 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,7 @@ function isMcpConfigured(entry: McpEntry): entry is ConfigMCPV1.Info {
115115
const sanitize = (s: string) => s.replace(/[^a-zA-Z0-9_-]/g, "_")
116116
const MAX_LIST_PAGES = 1_000
117117

118-
function remoteURL(key: string, value: string) {
118+
function remoteURL(value: string) {
119119
if (URL.canParse(value)) return new URL(value)
120120
}
121121

@@ -197,11 +197,7 @@ function convertMcpTool(mcpTool: MCPToolDef, client: MCPClient, timeout?: number
197197
}
198198

199199
function defs(client: MCPClient, timeout?: number) {
200-
return listTools(client, timeout ?? DEFAULT_TIMEOUT).pipe(
201-
Effect.catch((err) => {
202-
return Effect.succeed(undefined)
203-
}),
204-
)
200+
return listTools(client, timeout ?? DEFAULT_TIMEOUT).pipe(Effect.catch(() => Effect.void))
205201
}
206202

207203
function fetchFromClient<T extends { name: string }>(
@@ -212,9 +208,7 @@ function fetchFromClient<T extends { name: string }>(
212208
) {
213209
return Effect.tryPromise({
214210
try: () => listFn(client),
215-
catch: (e: any) => {
216-
return e
217-
},
211+
catch: (error) => error,
218212
}).pipe(
219213
Effect.tapError((error) =>
220214
Effect.logWarning(`failed to get ${label}`, {
@@ -323,7 +317,7 @@ export const layer = Layer.effect(
323317
) {
324318
const oauthDisabled = mcp.oauth === false
325319
const oauthConfig = typeof mcp.oauth === "object" ? mcp.oauth : undefined
326-
const url = remoteURL(key, mcp.url)
320+
const url = remoteURL(mcp.url)
327321
if (!url) {
328322
return {
329323
client: undefined as MCPClient | undefined,
@@ -407,12 +401,10 @@ export const layer = Layer.effect(
407401
}
408402

409403
lastStatus = { status: "failed" as const, error: lastError.message }
410-
return Effect.succeed(undefined)
404+
return Effect.void
411405
}),
412406
)
413-
if (result) {
414-
return { client: result.client as MCPClient | undefined, status: { status: "connected" } as Status }
415-
}
407+
if (result) return { client: result.client, status: { status: "connected" } as Status }
416408
// If this was an auth error, stop trying other transports
417409
if (lastStatus?.status === "needs_auth" || lastStatus?.status === "needs_client_registration") break
418410
}
@@ -486,8 +478,8 @@ export const layer = Layer.effect(
486478
if (process.platform === "win32") return [] as number[]
487479
const pids: number[] = []
488480
const queue = [pid]
489-
while (queue.length > 0) {
490-
const current = queue.shift()!
481+
for (let index = 0; index < queue.length; index++) {
482+
const current = queue[index]
491483
const handle = yield* spawner.spawn(ChildProcess.make("pgrep", ["-P", String(current)], { stdin: "ignore" }))
492484
const text = yield* Stream.mkString(Stream.decodeText(handle.stdout))
493485
yield* handle.exitCode
@@ -674,30 +666,20 @@ export const layer = Layer.effect(
674666
const config = cfg.mcp ?? {}
675667
const defaultTimeout = cfg.experimental?.mcp_timeout
676668

677-
const connectedClients = Object.entries(s.clients).filter(
678-
([clientName]) => s.status[clientName]?.status === "connected",
679-
)
680-
681-
yield* Effect.forEach(
682-
connectedClients,
683-
([clientName, client]) =>
684-
Effect.gen(function* () {
685-
const mcpConfig = config[clientName]
686-
const entry = mcpConfig && isMcpConfigured(mcpConfig) ? mcpConfig : s.config[clientName]
687-
688-
const listed = s.defs[clientName]
689-
if (!listed) {
690-
yield* Effect.logWarning("missing cached tools for connected server", { clientName })
691-
return
692-
}
693-
694-
const timeout = entry?.timeout ?? defaultTimeout
695-
for (const mcpTool of listed) {
696-
result[sanitize(clientName) + "_" + sanitize(mcpTool.name)] = convertMcpTool(mcpTool, client, timeout)
697-
}
698-
}),
699-
{ concurrency: "unbounded" },
700-
)
669+
for (const [clientName, client] of Object.entries(s.clients)) {
670+
if (s.status[clientName]?.status !== "connected") continue
671+
const mcpConfig = config[clientName]
672+
const entry = mcpConfig && isMcpConfigured(mcpConfig) ? mcpConfig : s.config[clientName]
673+
const listed = s.defs[clientName]
674+
if (!listed) {
675+
yield* Effect.logWarning("missing cached tools for connected server", { clientName })
676+
continue
677+
}
678+
const timeout = entry?.timeout ?? defaultTimeout
679+
for (const mcpTool of listed) {
680+
result[sanitize(clientName) + "_" + sanitize(mcpTool.name)] = convertMcpTool(mcpTool, client, timeout)
681+
}
682+
}
701683
return result
702684
})
703685

@@ -758,9 +740,7 @@ export const layer = Layer.effect(
758740
}
759741
return yield* Effect.tryPromise({
760742
try: () => fn(client),
761-
catch: (e: any) => {
762-
return e
763-
},
743+
catch: (error) => error,
764744
}).pipe(
765745
Effect.tapError((error) =>
766746
Effect.logError(`failed to ${label}`, {
@@ -809,7 +789,7 @@ export const layer = Layer.effect(
809789
const mcpConfig = yield* requireMcpConfig(mcpName)
810790
if (mcpConfig.type !== "remote") throw new Error(`MCP server ${mcpName} is not a remote server`)
811791
if (mcpConfig.oauth === false) throw new Error(`MCP server ${mcpName} has OAuth explicitly disabled`)
812-
const url = remoteURL(mcpName, mcpConfig.url)
792+
const url = remoteURL(mcpConfig.url)
813793
if (!url) throw new Error(`Invalid MCP URL for "${mcpName}"`)
814794

815795
// OAuth config is optional - if not provided, we'll use auto-discovery
@@ -881,7 +861,7 @@ export const layer = Layer.effect(
881861
: undefined
882862
if (!client || !listed) {
883863
yield* Effect.tryPromise(() => client?.close() ?? Promise.resolve()).pipe(Effect.ignore)
884-
return { status: "failed", error: "Failed to get tools" } as Status
864+
return { status: "failed", error: "Failed to get tools" } satisfies Status
885865
}
886866

887867
const s = yield* InstanceState.get(state)
@@ -936,7 +916,7 @@ export const layer = Layer.effect(
936916
}).pipe(Effect.option)
937917

938918
if (Option.isNone(result)) {
939-
return { status: "failed", error: "OAuth completion failed" } as Status
919+
return { status: "failed", error: "OAuth completion failed" } satisfies Status
940920
}
941921

942922
yield* auth.clearCodeVerifier(mcpName)
@@ -965,9 +945,9 @@ export const layer = Layer.effect(
965945

966946
const getAuthStatus = Effect.fn("MCP.getAuthStatus")(function* (mcpName: string) {
967947
const entry = yield* auth.get(mcpName)
968-
if (!entry?.tokens) return "not_authenticated" as AuthStatus
948+
if (!entry?.tokens) return "not_authenticated"
969949
const expired = yield* auth.isTokenExpired(mcpName)
970-
return (expired ? "expired" : "authenticated") as AuthStatus
950+
return expired ? "expired" : "authenticated"
971951
})
972952

973953
return Service.of({

0 commit comments

Comments
 (0)