mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-21 04:12:08 +03:00
refactor(core): remove duplicated MCP state and dead checks (#61156)
This commit is contained in:
committed by
GitHub
Unverified
parent
94f3386a90
commit
15d5e3f592
@@ -452,7 +452,7 @@ export const connect = Effect.fnUntraced(function* (
|
||||
).pipe(Effect.map((r) => r.resourceTemplates))
|
||||
: Effect.succeed([]),
|
||||
readResource: (input) => {
|
||||
if (!client.getServerCapabilities()?.resources) return Effect.succeed(undefined)
|
||||
if (!advertised("resources")) return Effect.succeed(undefined)
|
||||
return request("read MCP resource", (signal) =>
|
||||
client.readResource({ uri: input.uri }, { signal, timeout: execution }),
|
||||
)
|
||||
@@ -473,7 +473,8 @@ export const connect = Effect.fnUntraced(function* (
|
||||
{
|
||||
signal,
|
||||
timeout: execution,
|
||||
// Requesting progress keeps long calls alive under the SDK's timeout; execution is the hard wall.
|
||||
// Only asks for a progress token: progress on the response stream can keep proxies from closing it.
|
||||
// The SDK timeout does not reset on progress; execution is the hard wall.
|
||||
onprogress: () => {},
|
||||
// Always passed, even for a tool we haven't listed, so the SDK never falls back to listing
|
||||
// and caching the raw tools itself. Its types are narrower than what it reads (JSON values,
|
||||
@@ -490,8 +491,7 @@ export const connect = Effect.fnUntraced(function* (
|
||||
// so relist and retry once with the fresh definition.
|
||||
return call.pipe(
|
||||
Effect.catchIf(
|
||||
(error) =>
|
||||
client.getProtocolEra() === "modern" && error instanceof ProtocolError && error.code === HEADER_MISMATCH,
|
||||
(error) => connection.modern && error instanceof ProtocolError && error.code === HEADER_MISMATCH,
|
||||
() => connection.tools().pipe(Effect.andThen(call)),
|
||||
),
|
||||
Effect.mapError(failure),
|
||||
@@ -557,8 +557,8 @@ function toCallToolResult(result: SdkCallToolResult): CallToolResult {
|
||||
if (part.type === "resource_link") return [{ type: "text", text: part.uri }]
|
||||
if (part.type === "resource") {
|
||||
const resource = part.resource
|
||||
if ("text" in resource && typeof resource.text === "string") return [{ type: "text", text: resource.text }]
|
||||
if ("blob" in resource && typeof resource.blob === "string" && typeof resource.mimeType === "string")
|
||||
if ("text" in resource) return [{ type: "text", text: resource.text }]
|
||||
if ("blob" in resource && resource.mimeType !== undefined)
|
||||
return [{ type: "media", data: resource.blob, mimeType: resource.mimeType, uri: resource.uri }]
|
||||
return [{ type: "text", text: resource.uri }]
|
||||
}
|
||||
|
||||
@@ -34,12 +34,12 @@ export interface ServerInstructions {
|
||||
readonly instructions: string
|
||||
}
|
||||
|
||||
/** SDK tool definition tagged with the server that owns it. */
|
||||
/** Checked MCP tool definition tagged with the server that owns it. */
|
||||
export type Tool = McpClient.Tool & { readonly server: ServerName; readonly codemode?: boolean }
|
||||
export type ToolResultContent = McpClient.CallToolContent
|
||||
export type ToolResult = McpClient.CallToolResult & { readonly server: ServerName; readonly tool: string }
|
||||
export type ToolResult = McpClient.CallToolResult
|
||||
export type Prompt = McpClient.Prompt & { readonly server: ServerName }
|
||||
export type PromptResult = McpClient.GetPromptResult & { readonly server: ServerName; readonly name: string }
|
||||
export type PromptResult = McpClient.GetPromptResult
|
||||
|
||||
export const Resource = Mcp.Resource
|
||||
export type Resource = Mcp.Resource
|
||||
@@ -212,7 +212,6 @@ export const layer = (options?: Options) =>
|
||||
|
||||
// Register every remote server as an OAuth integration so credentials live in the global store
|
||||
// rather than in committed config. Servers that connect anonymously simply never use the method.
|
||||
const owned = new Set<Integration.ID>()
|
||||
const register = Effect.fnUntraced(function* (name: ServerName, entry: ServerEntry) {
|
||||
if (entry.config.type !== "remote" || entry.config.oauth === false) return
|
||||
const remote = entry.config
|
||||
@@ -226,7 +225,6 @@ export const layer = (options?: Options) =>
|
||||
.slice(0, 16)
|
||||
const integrationID = Integration.ID.make(suffix)
|
||||
entry.integrationID = integrationID
|
||||
owned.add(integrationID)
|
||||
const methodID = Integration.MethodID.make(suffix)
|
||||
// Each registration gets its own child scope so disposal detaches it from the root scope
|
||||
// entirely; registering directly on root would accumulate a dead finalizer per replaced or
|
||||
@@ -256,7 +254,7 @@ export const layer = (options?: Options) =>
|
||||
const requireServer = Effect.fnUntraced(function* (name: ServerName) {
|
||||
const entry = entries.get(name)
|
||||
if (!entry) return yield* new NotFoundError({ server: name })
|
||||
return { name, entry }
|
||||
return entry
|
||||
})
|
||||
|
||||
const connectProvider = Effect.fnUntraced(function* (entry: ServerEntry) {
|
||||
@@ -278,7 +276,7 @@ export const layer = (options?: Options) =>
|
||||
const formID = Form.ID.create()
|
||||
// Legacy only: 2026-07-28 has no elicitationId and no completion notification, so the form
|
||||
// settles when the user confirms and the SDK retries the tool call itself.
|
||||
const elicitationID: string | undefined = input.params.elicitationId
|
||||
const elicitationID = input.params.elicitationId
|
||||
const key = elicitationID === undefined ? undefined : input.server + "\u0000" + elicitationID
|
||||
if (key) urlElicitations.set(key, formID)
|
||||
return yield* forms
|
||||
@@ -400,9 +398,9 @@ export const layer = (options?: Options) =>
|
||||
yield* entry.connection.stop
|
||||
yield* bus.publish(McpEvent.StatusChanged, { server: name })
|
||||
}),
|
||||
toolsChanged: Effect.suspend(() => bus.publish(McpEvent.ToolsChanged, { server: name })),
|
||||
promptsChanged: Effect.suspend(() => bus.publish(PromptsChanged, { server: name })),
|
||||
resourcesChanged: Effect.suspend(() => bus.publish(McpEvent.ResourcesChanged, { server: name })),
|
||||
toolsChanged: bus.publish(McpEvent.ToolsChanged, { server: name }),
|
||||
promptsChanged: bus.publish(PromptsChanged, { server: name }),
|
||||
resourcesChanged: bus.publish(McpEvent.ResourcesChanged, { server: name }),
|
||||
},
|
||||
}),
|
||||
}
|
||||
@@ -421,7 +419,7 @@ export const layer = (options?: Options) =>
|
||||
(tool): Tool => ({
|
||||
...tool,
|
||||
server: name,
|
||||
...(entry.config.codemode === undefined ? {} : { codemode: entry.config.codemode }),
|
||||
codemode: entry.config.codemode,
|
||||
}),
|
||||
),
|
||||
}
|
||||
@@ -450,15 +448,14 @@ export const layer = (options?: Options) =>
|
||||
),
|
||||
})
|
||||
|
||||
const disposeServer = Effect.fnUntraced(function* (name: ServerName, entry: ServerEntry) {
|
||||
const disposeServer = Effect.fnUntraced(function* (entry: ServerEntry) {
|
||||
yield* entry.connection.stop
|
||||
if (entry.integrationID) owned.delete(entry.integrationID)
|
||||
if (entry.registration) yield* entry.registration.dispose
|
||||
})
|
||||
|
||||
const replaceServer = Effect.fnUntraced(function* (name: ServerName, serverConfig: Mcp.ServerConfig) {
|
||||
const previous = entries.get(name)
|
||||
if (previous) yield* disposeServer(name, previous)
|
||||
if (previous) yield* disposeServer(previous)
|
||||
const entry = makeEntry(name, serverConfig, yield* Clock.currentTimeMillis)
|
||||
entries.set(name, entry)
|
||||
yield* Effect.gen(function* () {
|
||||
@@ -475,10 +472,8 @@ export const layer = (options?: Options) =>
|
||||
)
|
||||
})
|
||||
|
||||
const removeServer = Effect.fnUntraced(function* (name: ServerName) {
|
||||
const entry = entries.get(name)
|
||||
if (!entry) return
|
||||
yield* disposeServer(name, entry)
|
||||
const removeServer = Effect.fnUntraced(function* (name: ServerName, entry: ServerEntry) {
|
||||
yield* disposeServer(entry)
|
||||
// Credentials are keyed by name + URL and intentionally survive removal for a later re-add.
|
||||
entries.delete(name)
|
||||
yield* bus.publish(McpEvent.StatusChanged, { server: name })
|
||||
@@ -492,8 +487,6 @@ export const layer = (options?: Options) =>
|
||||
if (!stack.includes(entry)) return
|
||||
const remaining = stack.filter((item) => item !== entry)
|
||||
const next = remaining.at(-1)
|
||||
// Already detaching; closing the scope must not schedule a second detach.
|
||||
entry.client.onClose(() => {})
|
||||
if (!next) {
|
||||
attached.delete(name)
|
||||
yield* Scope.close(entry.scope, Exit.void)
|
||||
@@ -583,18 +576,18 @@ export const layer = (options?: Options) =>
|
||||
)
|
||||
})
|
||||
|
||||
let applied: Map<ServerName, Mcp.ServerConfig> | undefined
|
||||
let booted = false
|
||||
const overrides = new Map<ServerName, Mcp.ServerConfig | false>()
|
||||
const reconcileLock = Semaphore.makeUnsafe(1)
|
||||
const reconcile = Effect.fnUntraced(function* () {
|
||||
const servers = state.get().servers
|
||||
if (!applied && entries.size === 0) {
|
||||
if (!booted) {
|
||||
booted = true
|
||||
const started = yield* Clock.currentTimeMillis
|
||||
for (const [name, server] of servers) {
|
||||
entries.set(name, makeEntry(name, server, started))
|
||||
}
|
||||
yield* Effect.forEach(entries, ([name, entry]) => register(name, entry), { discard: true })
|
||||
applied = servers
|
||||
|
||||
// Initial connections stay asynchronous so one slow server does not block Location startup.
|
||||
for (const [name, entry] of entries) {
|
||||
@@ -615,18 +608,14 @@ export const layer = (options?: Options) =>
|
||||
return
|
||||
}
|
||||
|
||||
const names = new Set([...(applied?.keys() ?? []), ...servers.keys()])
|
||||
for (const name of names) {
|
||||
const previous = applied?.get(name)
|
||||
for (const [name, entry] of entries) {
|
||||
const updated = servers.get(name)
|
||||
if (isDeepStrictEqual(previous, updated)) continue
|
||||
if (!updated) {
|
||||
yield* removeServer(name).pipe(locks.withLock(name))
|
||||
continue
|
||||
}
|
||||
yield* replaceServer(name, updated).pipe(locks.withLock(name))
|
||||
if (isDeepStrictEqual(entry.config, updated)) continue
|
||||
yield* (updated ? replaceServer(name, updated) : removeServer(name, entry)).pipe(locks.withLock(name))
|
||||
}
|
||||
for (const [name, updated] of servers) {
|
||||
if (!entries.has(name)) yield* replaceServer(name, updated).pipe(locks.withLock(name))
|
||||
}
|
||||
applied = servers
|
||||
})
|
||||
|
||||
// Bring a server online (or back to needs_auth) when its integration's credential changes, so an
|
||||
@@ -646,10 +635,9 @@ export const layer = (options?: Options) =>
|
||||
}).pipe(locks.withLock(name))
|
||||
})
|
||||
fork(
|
||||
bus.subscribe(Credential.Event.Switched).pipe(
|
||||
Stream.filter((event) => owned.has(event.data.integrationID)),
|
||||
Stream.runForEach((event) => Effect.sync(() => fork(reconnect(event.data.integrationID)))),
|
||||
),
|
||||
bus
|
||||
.subscribe(Credential.Event.Switched)
|
||||
.pipe(Stream.runForEach((event) => Effect.sync(() => fork(reconnect(event.data.integrationID))))),
|
||||
)
|
||||
const state: State.Interface<Data, Editor> = State.create<Data, Editor>({
|
||||
name: "mcp",
|
||||
@@ -702,17 +690,17 @@ export const layer = (options?: Options) =>
|
||||
connect: Effect.fn("MCP.connect")(function* (server) {
|
||||
const name = ServerName.make(server)
|
||||
yield* Effect.gen(function* () {
|
||||
const target = yield* requireServer(name)
|
||||
yield* target.entry.connection.stop
|
||||
yield* target.entry.connection.start
|
||||
const entry = yield* requireServer(name)
|
||||
yield* entry.connection.stop
|
||||
yield* entry.connection.start
|
||||
}).pipe(locks.withLock(name))
|
||||
}),
|
||||
disconnect: Effect.fn("MCP.disconnect")(function* (server) {
|
||||
const name = ServerName.make(server)
|
||||
yield* Effect.gen(function* () {
|
||||
const target = yield* requireServer(name)
|
||||
yield* target.entry.connection.stop
|
||||
target.entry.status = { status: "disabled" }
|
||||
const entry = yield* requireServer(name)
|
||||
yield* entry.connection.stop
|
||||
entry.status = { status: "disabled" }
|
||||
yield* bus.publish(McpEvent.StatusChanged, { server: name })
|
||||
}).pipe(locks.withLock(name))
|
||||
}),
|
||||
@@ -750,48 +738,28 @@ export const layer = (options?: Options) =>
|
||||
}),
|
||||
callTool: Effect.fn("MCP.callTool")(function* (input) {
|
||||
const server = ServerName.make(input.server)
|
||||
const call = (connection: McpClient.Connection) =>
|
||||
connection.callTool({ name: input.name, args: input.args, sessionID: input.sessionID })
|
||||
const failed = (owner: string) =>
|
||||
Effect.mapError(
|
||||
(error: Error) =>
|
||||
new ToolCallError({
|
||||
server,
|
||||
tool: input.name,
|
||||
message: `MCP tool "${input.name}" on ${owner} "${server}" failed: ${error.message}`,
|
||||
}),
|
||||
)
|
||||
// An attached client owns the tools it lists, even when a configured server shares its name, and
|
||||
// owns its name outright when no configured server has it.
|
||||
const client = attached.get(server)?.at(-1)
|
||||
if (client && (client.tools.some((tool) => tool.name === input.name) || !entries.has(server))) {
|
||||
const result = yield* client.client
|
||||
.callTool({ name: input.name, args: input.args, sessionID: input.sessionID })
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new ToolCallError({
|
||||
server,
|
||||
tool: input.name,
|
||||
message: `MCP tool "${input.name}" on client "${server}" failed: ${error.message}`,
|
||||
}),
|
||||
),
|
||||
)
|
||||
return { ...result, server, tool: input.name }
|
||||
}
|
||||
const target = yield* requireServer(server)
|
||||
yield* target.entry.startup.await
|
||||
const connected = target.entry.connection.client
|
||||
if (client && (client.tools.some((tool) => tool.name === input.name) || !entries.has(server)))
|
||||
return yield* call(client.client).pipe(failed("client"))
|
||||
const entry = yield* requireServer(server)
|
||||
yield* entry.startup.await
|
||||
const connected = entry.connection.client
|
||||
if (!connected)
|
||||
return yield* new ToolCallError({
|
||||
server: target.name,
|
||||
tool: input.name,
|
||||
message: unavailable(target.name, target.entry.status),
|
||||
})
|
||||
const result = yield* target.entry.connection
|
||||
.recovering(connected, (connection) =>
|
||||
connection.callTool({ name: input.name, args: input.args, sessionID: input.sessionID }),
|
||||
)
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new ToolCallError({
|
||||
server: target.name,
|
||||
tool: input.name,
|
||||
message: `MCP tool "${input.name}" on server "${target.name}" failed: ${error.message}`,
|
||||
}),
|
||||
),
|
||||
)
|
||||
return { ...result, server: target.name, tool: input.name }
|
||||
return yield* new ToolCallError({ server, tool: input.name, message: unavailable(server, entry.status) })
|
||||
return yield* entry.connection.recovering(connected, call).pipe(failed("server"))
|
||||
}),
|
||||
instructions: Effect.fn("MCP.instructions")(function* () {
|
||||
return Array.from(entries)
|
||||
@@ -810,15 +778,13 @@ export const layer = (options?: Options) =>
|
||||
.toSorted((a, b) => a.server.localeCompare(b.server) || a.name.localeCompare(b.name))
|
||||
}),
|
||||
prompt: Effect.fn("MCP.prompt")(function* (input) {
|
||||
const target = yield* requireServer(ServerName.make(input.server))
|
||||
yield* target.entry.startup.await
|
||||
const client = target.entry.connection.client
|
||||
const entry = yield* requireServer(ServerName.make(input.server))
|
||||
yield* entry.startup.await
|
||||
const client = entry.connection.client
|
||||
if (!client) return undefined
|
||||
const result = yield* target.entry.connection
|
||||
return yield* entry.connection
|
||||
.recovering(client, (connection) => connection.prompt({ name: input.name, args: input.args }))
|
||||
.pipe(Effect.orElseSucceed(() => undefined))
|
||||
if (!result) return undefined
|
||||
return { ...result, server: target.name, name: input.name }
|
||||
}),
|
||||
resourceCatalog: Effect.fn("MCP.resourceCatalog")(function* () {
|
||||
const empty = ResourceCatalog.make({ resources: [], templates: [] })
|
||||
@@ -836,23 +802,25 @@ export const layer = (options?: Options) =>
|
||||
return mergeCatalogs(catalogs)
|
||||
}),
|
||||
resources: Effect.fn("MCP.resources")(function* (input) {
|
||||
const target = yield* requireServer(ServerName.make(input.server))
|
||||
yield* target.entry.startup.await
|
||||
const client = target.entry.connection.client
|
||||
const name = ServerName.make(input.server)
|
||||
const entry = yield* requireServer(name)
|
||||
yield* entry.startup.await
|
||||
const client = entry.connection.client
|
||||
if (!client) return ResourceCatalog.make({ resources: [], templates: [] })
|
||||
return mergeCatalogs([toCatalog(target.name, yield* target.entry.connection.catalog(client))])
|
||||
return mergeCatalogs([toCatalog(name, yield* entry.connection.catalog(client))])
|
||||
}),
|
||||
readResource: Effect.fn("MCP.readResource")(function* (input) {
|
||||
const target = yield* requireServer(ServerName.make(input.server))
|
||||
yield* target.entry.startup.await
|
||||
const client = target.entry.connection.client
|
||||
const name = ServerName.make(input.server)
|
||||
const entry = yield* requireServer(name)
|
||||
yield* entry.startup.await
|
||||
const client = entry.connection.client
|
||||
if (!client) return undefined
|
||||
const result = yield* target.entry.connection.recovering(client, (connection) =>
|
||||
const result = yield* entry.connection.recovering(client, (connection) =>
|
||||
connection.readResource({ uri: input.uri }),
|
||||
)
|
||||
if (!result) return undefined
|
||||
return ResourceContent.make({
|
||||
server: target.name,
|
||||
server: name,
|
||||
uri: input.uri,
|
||||
contents: result.contents.map((part) =>
|
||||
"text" in part
|
||||
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
import { OAuthMetadataSchema, OpenIdProviderDiscoveryMetadataSchema } from "@modelcontextprotocol/core"
|
||||
import { Cause, Deferred, Effect } from "effect"
|
||||
import type { ServerResponse } from "node:http"
|
||||
import type { AddressInfo } from "node:net"
|
||||
import { ConfigMCP } from "@opencode/schema/config/mcp"
|
||||
import { noTimeoutFetch } from "@opencode/util/no-timeout-fetch"
|
||||
import { Credential } from "../credential.js"
|
||||
@@ -106,7 +107,7 @@ export const loggedFetch = (fields: { readonly server: string; readonly director
|
||||
|
||||
// A configured authorization server document stands in for RFC 9728 discovery: the SDK reuses this
|
||||
// state instead of probing the resource server, whose well-known path may not exist.
|
||||
export const configuredDiscovery = async (input: {
|
||||
const configuredDiscovery = async (input: {
|
||||
readonly config: typeof ConfigMCP.Remote.Type
|
||||
readonly fetchFn: FetchLike
|
||||
}): Promise<OAuthDiscoveryState | undefined> => {
|
||||
@@ -123,7 +124,7 @@ export const configuredDiscovery = async (input: {
|
||||
}
|
||||
}
|
||||
|
||||
export interface Store {
|
||||
interface Store {
|
||||
readonly tokens: () => Promise<StoredOAuthTokens | undefined>
|
||||
readonly saveTokens: (tokens: StoredOAuthTokens) => Promise<void>
|
||||
readonly clientInformation: () => Promise<StoredOAuthClientInformation | undefined>
|
||||
@@ -132,7 +133,7 @@ export interface Store {
|
||||
readonly saveCodeVerifier: (verifier: string) => Promise<void>
|
||||
}
|
||||
|
||||
export interface Options {
|
||||
interface Options {
|
||||
readonly config: typeof ConfigMCP.Remote.Type
|
||||
readonly store: Store
|
||||
/** Absent on connect: the provider then refuses to register a client or redirect, ending in needs_auth. */
|
||||
@@ -146,7 +147,7 @@ export interface Options {
|
||||
readonly invalidate?: OAuthClientProvider["invalidateCredentials"]
|
||||
}
|
||||
|
||||
export const provider = (options: Options): OAuthClientProvider => {
|
||||
const provider = (options: Options): OAuthClientProvider => {
|
||||
const oauth = options.config.oauth || undefined
|
||||
const client = oauth?.client_id ? { client_id: oauth.client_id, client_secret: oauth.client_secret } : undefined
|
||||
const redirect = options.redirect
|
||||
@@ -214,7 +215,7 @@ export const provider = (options: Options): OAuthClientProvider => {
|
||||
}
|
||||
}
|
||||
|
||||
export const memoryStore = (): Store => {
|
||||
const memoryStore = (): Store => {
|
||||
let tokens: StoredOAuthTokens | undefined
|
||||
let client: StoredOAuthClientInformation | undefined
|
||||
let verifier: string | undefined
|
||||
@@ -237,7 +238,7 @@ export const memoryStore = (): Store => {
|
||||
export const clientFromCredential = (credential: Credential.OAuth) =>
|
||||
credential.metadata?.client as StoredOAuthClientInformation | undefined
|
||||
|
||||
export const toCredential = (input: {
|
||||
const toCredential = (input: {
|
||||
readonly methodID: Integration.MethodID
|
||||
readonly serverUrl: string
|
||||
readonly tokens: StoredOAuthTokens
|
||||
@@ -259,7 +260,7 @@ export const toCredential = (input: {
|
||||
},
|
||||
})
|
||||
|
||||
export const toTokens = (credential: Credential.OAuth): StoredOAuthTokens => {
|
||||
const toTokens = (credential: Credential.OAuth): StoredOAuthTokens => {
|
||||
const metadata = credential.metadata ?? {}
|
||||
return {
|
||||
access_token: credential.access,
|
||||
@@ -397,12 +398,7 @@ export const authorize = (input: {
|
||||
const port = yield* Effect.callback<number, Error>((resume) => {
|
||||
server.once("error", (error) => resume(Effect.fail(error)))
|
||||
server.listen(oauth?.callback_port ?? redirectPort ?? 0, "127.0.0.1", () => {
|
||||
const address = server.address()
|
||||
resume(
|
||||
address && typeof address === "object"
|
||||
? Effect.succeed(address.port)
|
||||
: Effect.fail(new Error("Could not determine MCP OAuth callback port")),
|
||||
)
|
||||
resume(Effect.succeed((server.address() as AddressInfo).port))
|
||||
})
|
||||
})
|
||||
yield* Effect.addFinalizer(() => Effect.sync(() => server.close()))
|
||||
|
||||
@@ -66,10 +66,8 @@ export function make(socket: Socket): SocketTransport {
|
||||
}),
|
||||
close: () => {
|
||||
if (phase === "closed") return Promise.resolve()
|
||||
phase = "closed"
|
||||
pending.length = 0
|
||||
const closed = Result.try(() => socket.close(1000))
|
||||
transport.onclose?.()
|
||||
finish()
|
||||
return Result.isFailure(closed) ? Promise.reject(closed.failure) : Promise.resolve()
|
||||
},
|
||||
deliver: (text) => {
|
||||
|
||||
@@ -60,8 +60,7 @@ export const make = Effect.fnUntraced(function* (options: Options) {
|
||||
const stop = Effect.fnUntraced(function* (handle: ChildProcessHandle) {
|
||||
// Exit completion can precede descendant cleanup after the capture deadline.
|
||||
yield* Effect.timeoutOption(handle.exitCode, CLOSE_GRACE).pipe(Effect.ignore)
|
||||
const terminated = yield* Effect.timeoutOption(handle.kill({ killSignal: "SIGTERM" }), FORCE_KILL_AFTER)
|
||||
if (terminated._tag === "None") yield* handle.kill({ killSignal: "SIGKILL" })
|
||||
yield* handle.kill({ killSignal: "SIGTERM", forceKillAfter: FORCE_KILL_AFTER })
|
||||
}, Effect.ignore())
|
||||
|
||||
const close = () =>
|
||||
|
||||
@@ -54,7 +54,7 @@ export const layer = Layer.effect(
|
||||
name: tool.name,
|
||||
options: { namespace: namespace(tool.server), codemode: tool.codemode !== false },
|
||||
description: tool.description ?? "",
|
||||
input: (tool.inputSchema ?? { type: "object", properties: {} }) as JsonSchema.JsonSchema,
|
||||
input: tool.inputSchema as JsonSchema.JsonSchema,
|
||||
output: (tool.outputSchema ?? {}) as JsonSchema.JsonSchema,
|
||||
execute: (input, context) =>
|
||||
Effect.gen(function* () {
|
||||
|
||||
@@ -382,16 +382,17 @@ function resourceMcpLayer(
|
||||
Layer.succeed(Location.Service, Location.Service.of(location({ directory }))),
|
||||
Layer.mock(Bus.Service, {
|
||||
subscribe: overrides?.subscribe ?? (() => Stream.never),
|
||||
publish: (definition, data) => {
|
||||
const event = {
|
||||
id: ID.create(),
|
||||
type: definition.type,
|
||||
data,
|
||||
} as Payload<typeof definition>
|
||||
overrides?.published?.push(event.type)
|
||||
if (event.type !== Form.Event.Created.type || !onFormCreated) return Effect.succeed(event)
|
||||
return onFormCreated(Schema.decodeUnknownSync(Form.Event.Created.data)(data).form).pipe(Effect.as(event))
|
||||
},
|
||||
publish: (definition, data) =>
|
||||
Effect.suspend(() => {
|
||||
const event = {
|
||||
id: ID.create(),
|
||||
type: definition.type,
|
||||
data,
|
||||
} as Payload<typeof definition>
|
||||
overrides?.published?.push(event.type)
|
||||
if (event.type !== Form.Event.Created.type || !onFormCreated) return Effect.succeed(event)
|
||||
return onFormCreated(Schema.decodeUnknownSync(Form.Event.Created.data)(data).form).pipe(Effect.as(event))
|
||||
}),
|
||||
}),
|
||||
Layer.mock(Integration.Service, {
|
||||
revision: () => 0,
|
||||
@@ -518,15 +519,11 @@ const mcp = Layer.mock(Mcp.Service, {
|
||||
invocations.push(input)
|
||||
if (input.name === "fail")
|
||||
return {
|
||||
server: Mcp.ServerName.make(input.server),
|
||||
tool: input.name,
|
||||
isError: true,
|
||||
content: [{ type: "text", text: "search index unavailable" }],
|
||||
} satisfies Mcp.ToolResult
|
||||
if (input.name === "media")
|
||||
return {
|
||||
server: Mcp.ServerName.make(input.server),
|
||||
tool: input.name,
|
||||
isError: false,
|
||||
content: [
|
||||
{ type: "text", text: "rendered chart" },
|
||||
@@ -535,8 +532,6 @@ const mcp = Layer.mock(Mcp.Service, {
|
||||
} satisfies Mcp.ToolResult
|
||||
if (input.name === "attachments")
|
||||
return {
|
||||
server: Mcp.ServerName.make(input.server),
|
||||
tool: input.name,
|
||||
isError: false,
|
||||
content: [
|
||||
{
|
||||
@@ -555,28 +550,20 @@ const mcp = Layer.mock(Mcp.Service, {
|
||||
} satisfies Mcp.ToolResult
|
||||
if (input.name === "status")
|
||||
return {
|
||||
server: Mcp.ServerName.make(input.server),
|
||||
tool: input.name,
|
||||
isError: false,
|
||||
content: [{ type: "text", text: "hello" }],
|
||||
} satisfies Mcp.ToolResult
|
||||
if (input.name === "issues" || input.name === "typed")
|
||||
return {
|
||||
server: Mcp.ServerName.make(input.server),
|
||||
tool: input.name,
|
||||
isError: false,
|
||||
content: [{ type: "text", text: '{"issues":[{"id":1}]}' }],
|
||||
} satisfies Mcp.ToolResult
|
||||
if (input.name === "count")
|
||||
return {
|
||||
server: Mcp.ServerName.make(input.server),
|
||||
tool: input.name,
|
||||
isError: false,
|
||||
content: [{ type: "text", text: "42" }],
|
||||
} satisfies Mcp.ToolResult
|
||||
return {
|
||||
server: Mcp.ServerName.make(input.server),
|
||||
tool: input.name,
|
||||
isError: false,
|
||||
structured: { ok: true },
|
||||
content: [],
|
||||
@@ -2187,7 +2174,10 @@ test("reconciles only changed MCP server config", async () => {
|
||||
Effect.provide(
|
||||
resourceMcpLayer(resources(), undefined, undefined, {
|
||||
entries: () => Effect.sync(() => entries),
|
||||
subscribe: (() => Stream.fromPubSub(updates)) as Bus.Interface["subscribe"],
|
||||
subscribe: ((definition?: { readonly type: string }) =>
|
||||
Stream.fromPubSub(updates).pipe(
|
||||
Stream.filter((event) => !definition || event.type === definition.type),
|
||||
)) as Bus.Interface["subscribe"],
|
||||
}),
|
||||
),
|
||||
)
|
||||
@@ -2550,8 +2540,6 @@ testEffect(Layer.empty).live("preserves plugin transforms through MCP catalog up
|
||||
tools: () => Ref.get(catalog),
|
||||
callTool: (input) =>
|
||||
Effect.succeed({
|
||||
server: Mcp.ServerName.make(input.server),
|
||||
tool: input.name,
|
||||
isError: false,
|
||||
content: [{ type: "text", text: "healthy" }],
|
||||
} satisfies Mcp.ToolResult),
|
||||
@@ -3136,7 +3124,10 @@ for (const source of ["config", "organization"] as const) {
|
||||
Effect.provide(
|
||||
resourceMcpLayer(server.url, undefined, undefined, {
|
||||
entries: config.entries,
|
||||
subscribe: (() => Stream.fromPubSub(updates)) as Bus.Interface["subscribe"],
|
||||
subscribe: ((definition?: { readonly type: string }) =>
|
||||
Stream.fromPubSub(updates).pipe(
|
||||
Stream.filter((event) => !definition || event.type === definition.type),
|
||||
)) as Bus.Interface["subscribe"],
|
||||
}),
|
||||
),
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user