From c081e2839670aa5778eeb674830a699fd39a93d3 Mon Sep 17 00:00:00 2001 From: Yaacov Date: Sun, 22 Nov 2026 18:23:18 +0200 Subject: [PATCH] feat(extensions): sign in to Scient Agent MCP servers from the Installed page - With an agent that offers the mcp host command, the Installed page lists Scient Agent's MCP servers (Codex plugin servers included) from `mcp list`: connected with tool counts, needs sign-in, failed; file rows stay as the fallback and for disabled servers. - Sign in runs `mcp login ` in the sign-in's scope, returns the authorization URL, settles on completed/failed/early exit, then refreshes the inventory. - Older agents keep today's behavior and message. --- .../src/provider/Drivers/ScientAgentDriver.ts | 28 ++++ .../extensions/ProviderPluginCommand.ts | 116 ++++++++++++--- .../ScientAgentMcpInventory.test.ts | 132 ++++++++++++++++++ .../extensions/ScientAgentMcpInventory.ts | 131 +++++++++++++++++ .../extensions/ScientAgentPluginInventory.ts | 124 ++++++++++++---- 5 files changed, 483 insertions(+), 48 deletions(-) diff --git a/apps/server/src/provider/Drivers/ScientAgentDriver.ts b/apps/server/src/provider/Drivers/ScientAgentDriver.ts index 58b11b0fd6..9add234cae 100644 --- a/apps/server/src/provider/Drivers/ScientAgentDriver.ts +++ b/apps/server/src/provider/Drivers/ScientAgentDriver.ts @@ -63,6 +63,10 @@ import { runScientAgentPluginCommand, } from "../../scient/extensions/ScientAgentPluginInventory.ts"; import { readScientAgentMcpServers } from "../../scient/extensions/ScientAgentMcpInventory.ts"; +import { + runScientAgentHostCommand, + startScientAgentHostProcess, +} from "../../scient/extensions/ProviderPluginCommand.ts"; import { hasChatGptAccount, readScientAgentChatGptApps, @@ -443,6 +447,30 @@ export const ScientAgentDriver: ScientProviderDriver< Effect.provideService(FileSystem.FileSystem, fs), Effect.provideService(Path.Path, path), ), + { + list: (serverName) => + runScientAgentHostCommand(launchConfig.binaryPath, processEnv, serverConfig.stateDir, [ + "mcp", + "list", + ...(serverName === undefined ? [] : ["--server", serverName]), + ]).pipe( + Effect.provideService(OmpExecutableGate, executableGate), + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + Effect.provideService(FileSystem.FileSystem, fs), + Effect.provideService(Path.Path, path), + ), + login: (serverName) => + startScientAgentHostProcess(launchConfig.binaryPath, processEnv, serverConfig.stateDir, [ + "mcp", + "login", + serverName, + ]).pipe( + Effect.provideService(OmpExecutableGate, executableGate), + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + Effect.provideService(FileSystem.FileSystem, fs), + Effect.provideService(Path.Path, path), + ), + }, ).pipe(Effect.provideService(Path.Path, path)); const store = yield* makeSharedPluginStore({ kind: "scient", diff --git a/apps/server/src/scient/extensions/ProviderPluginCommand.ts b/apps/server/src/scient/extensions/ProviderPluginCommand.ts index 2941948ee9..b49d0f5654 100644 --- a/apps/server/src/scient/extensions/ProviderPluginCommand.ts +++ b/apps/server/src/scient/extensions/ProviderPluginCommand.ts @@ -7,7 +7,10 @@ import { canonicalOmpExecutablePath, OmpExecutableGate, } from "../../provider/omp/OmpExecutableGate.ts"; -import { scientAgentTarget } from "../../provider/scient/ScientAgentTarget.ts"; +import { + scientAgentHostCommands, + scientAgentTarget, +} from "../../provider/scient/ScientAgentTarget.ts"; const OUTPUT_LIMIT = 4 * 1024 * 1024; @@ -59,29 +62,102 @@ export const runProviderPluginCommand = Effect.fn("runProviderPluginCommand")( Effect.mapError(() => ({ message: "The agent plugin command failed or timed out." })), ); +/** + * Resolves and leases the executable in the caller's scope, then reads its runtime info once. + * Sources follow the identified build so plugin commands see what conversations load. + */ +const prepareScientAgent = Effect.fn("prepareScientAgent")(function* ( + executable: string, + env: NodeJS.ProcessEnv, + cwd: string, +) { + const resolved = + (yield* resolveCommandPath(executable, { env, bypassCache: true })) ?? executable; + const identity = yield* canonicalOmpExecutablePath(resolved); + const gate = yield* OmpExecutableGate; + yield* gate.acquireProcess(identity, { target: scientAgentTarget, kind: "one-shot" }); + const info = yield* runProviderPluginCommand(resolved, env, cwd, ["--runtime-info"]); + const runtime = scientAgentTarget.identify(info); + if (!runtime) return yield* Effect.fail({ message: scientAgentTarget.unsupportedDetail }); + return { + resolved, + hostCommands: scientAgentHostCommands(info), + env: { + ...env, + SCIENT_AGENT_ENABLE_SOURCES: supportsScientClaudePlugins(runtime.version) + ? "claude-plugins,codex-plugins" + : undefined, + }, + }; +}); + export const runScientAgentPluginCommand = Effect.fn("runScientAgentPluginCommand")( function* (executable: string, env: NodeJS.ProcessEnv, cwd: string, args: ReadonlyArray) { - const resolved = - (yield* resolveCommandPath(executable, { env, bypassCache: true })) ?? executable; - const identity = yield* canonicalOmpExecutablePath(resolved); - const gate = yield* OmpExecutableGate; - yield* gate.acquireProcess(identity, { target: scientAgentTarget, kind: "one-shot" }); - const info = yield* runProviderPluginCommand(resolved, env, cwd, ["--runtime-info"]); - const runtime = scientAgentTarget.identify(info); - if (!runtime) return yield* Effect.fail({ message: scientAgentTarget.unsupportedDetail }); - return yield* runProviderPluginCommand( - resolved, - { - ...env, - SCIENT_AGENT_ENABLE_SOURCES: supportsScientClaudePlugins(runtime.version) - ? "claude-plugins,codex-plugins" - : undefined, - }, - cwd, - args, - ); + const agent = yield* prepareScientAgent(executable, env, cwd); + return yield* runProviderPluginCommand(agent.resolved, agent.env, cwd, args); }, Effect.timeout("65 seconds"), Effect.scoped, Effect.mapError(() => ({ message: "Scient Agent could not complete the plugin command." })), ); + +/** + * Runs one of the agent's host commands, `undefined` when this build does not offer it (an older + * one would read the word as a prompt). Its JSON error answer exits 1, so stdout is kept. + */ +export const runScientAgentHostCommand = Effect.fn("runScientAgentHostCommand")( + function* ( + executable: string, + env: NodeJS.ProcessEnv, + cwd: string, + args: readonly [string, ...string[]], + ) { + const agent = yield* prepareScientAgent(executable, env, cwd); + if (!agent.hostCommands.includes(args[0])) return undefined; + return yield* runProviderPluginCommand(agent.resolved, agent.env, cwd, args, { + acceptNonZeroExit: true, + }); + }, + Effect.timeout("75 seconds"), + Effect.scoped, + Effect.mapError(() => ({ message: "Scient Agent could not complete the command." })), +); + +/** + * Starts a long-running host command in the caller's scope, which owns the process: closing it + * stops the command. `undefined` when this build does not offer it. Yields stdout lines. + */ +export const startScientAgentHostProcess = Effect.fn("startScientAgentHostProcess")( + function* ( + executable: string, + env: NodeJS.ProcessEnv, + cwd: string, + args: readonly [string, ...string[]], + ) { + const agent = yield* prepareScientAgent(executable, env, cwd); + if (!agent.hostCommands.includes(args[0])) return undefined; + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const childEnv = { ...agent.env, SCIENT_AGENT_HOST_PAGES: "1" }; + const command = yield* resolveSpawnCommand(agent.resolved, args, { + env: childEnv, + extendEnv: false, + }); + const child = yield* spawner.spawn( + ChildProcess.make(command.command, command.args, { + env: childEnv, + extendEnv: false, + cwd, + shell: command.shell, + stdin: "ignore", + stderr: "ignore", + forceKillAfter: "1 second", + }), + ); + return child.stdout.pipe( + Stream.decodeText(), + Stream.splitLines, + Stream.mapError(() => ({ message: "Scient Agent's output could not be read." })), + ); + }, + Effect.mapError(() => ({ message: "Scient Agent could not start the command." })), +); diff --git a/apps/server/src/scient/extensions/ScientAgentMcpInventory.test.ts b/apps/server/src/scient/extensions/ScientAgentMcpInventory.test.ts index bf59a7c925..82641dc9c5 100644 --- a/apps/server/src/scient/extensions/ScientAgentMcpInventory.test.ts +++ b/apps/server/src/scient/extensions/ScientAgentMcpInventory.test.ts @@ -1,5 +1,6 @@ import { NodeServices } from "@effect/platform-node"; import { describe, expect, it } from "@effect/vitest"; +import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; @@ -55,3 +56,134 @@ describe("Scient Agent standalone MCP inventory", () => { ).pipe(Effect.provide(NodeServices.layer)), ); }); + +describe("Scient Agent live MCP servers", () => { + const plugins = encode({ npm: [], marketplace: [] }); + const fileRows = [ + { name: "lab", scope: "user", status: "unknown" as const }, + { name: "off", scope: "user", status: "disabled" as const }, + { name: "Gmail", scope: "chatgpt", status: "connected" as const }, + ]; + const agentList = encode({ + servers: [ + { + name: "figma", + status: "needs-auth", + pluginId: "figma@openai-curated", + canStartSignIn: true, + }, + { name: "lab", status: "connected", scope: "user", toolCount: 3 }, + ], + }); + + it.effect("lets the agent's listing replace guessed rows and falls back when it fails", () => + Effect.scoped( + Effect.gen(function* () { + let answer: Effect.Effect = + Effect.succeed(agentList); + const requests: Array = []; + const native = yield* makeScientAgentPluginInventory( + () => Effect.succeed(plugins), + undefined, + () => Effect.succeed(fileRows), + { + list: (serverName) => + Effect.sync(() => requests.push(serverName)).pipe(Effect.andThen(answer)), + login: () => Effect.undefined, + }, + ); + yield* native.actions.refreshInventory!({ force: true }); + const live = yield* native.reports.pipe(Stream.runHead); + expect(live._tag === "Some" && live.value.mcpServers).toEqual([ + { + name: "figma", + status: "needs-auth", + pluginId: "figma@openai-curated", + canStartSignIn: true, + }, + { name: "lab", status: "connected", scope: "user", toolCount: 3 }, + fileRows[1], + fileRows[2], + ]); + expect(yield* native.actions.readMcpServer({ serverName: "figma" })).toMatchObject({ + canStartSignIn: true, + }); + expect(requests.at(-1)).toBe("figma"); + + answer = Effect.succeed(encode({ error: { message: "config unreadable" } })); + yield* native.actions.refreshInventory!({ force: true }); + const fallback = yield* native.reports.pipe(Stream.runHead); + expect(fallback._tag === "Some" && fallback.value.mcpServers).toEqual(fileRows); + expect( + (yield* native.actions.readMcpServer({ serverName: "figma" }).pipe(Effect.flip)).message, + ).toBe("config unreadable"); + }), + ).pipe(Effect.provide(NodeServices.layer)), + ); + + it.effect("keeps file rows and the agent-managed sign-in for an executable without mcp", () => + Effect.scoped( + Effect.gen(function* () { + const native = yield* makeScientAgentPluginInventory( + () => Effect.succeed(plugins), + undefined, + () => Effect.succeed(fileRows), + { list: () => Effect.undefined, login: () => Effect.undefined }, + ); + yield* native.actions.refreshInventory!({ force: true }); + const report = yield* native.reports.pipe(Stream.runHead); + expect(report._tag === "Some" && report.value.mcpServers).toEqual(fileRows); + expect(yield* native.actions.readMcpServer({ serverName: "lab" })).toBeUndefined(); + const failure = yield* native.actions + .startMcpSignIn({ serverName: "lab" }) + .pipe(Effect.flip); + expect(failure.message).toBe("Manage this MCP server's sign-in in Scient Agent."); + }), + ).pipe(Effect.provide(NodeServices.layer)), + ); + + it.effect("follows the login lines to completion, failure or an early exit", () => + Effect.scoped( + Effect.gen(function* () { + const url = encode({ type: "authorization_url", url: "https://auth.example/start" }); + let lines: ReadonlyArray = []; + const refreshed = yield* Deferred.make(); + let listed = 0; + const native = yield* makeScientAgentPluginInventory( + () => Effect.succeed(plugins), + undefined, + () => Effect.succeed([]), + { + list: () => + Effect.sync(() => ++listed).pipe( + Effect.tap(() => Deferred.succeed(refreshed, undefined)), + Effect.as(agentList), + ), + login: () => Effect.succeed(Stream.fromIterable(lines)), + }, + ); + const signIn = native.actions.startMcpSignIn({ serverName: "figma" }); + + lines = ["progress text", url, encode({ type: "completed" })]; + const attempt = yield* signIn; + expect(attempt.authorizationUrl).toBe("https://auth.example/start"); + yield* attempt.waitForCompletion; + yield* Deferred.await(refreshed); + expect(listed).toBe(1); + + lines = [url, encode({ type: "failed", message: "Access denied" })]; + expect((yield* (yield* signIn).waitForCompletion.pipe(Effect.flip)).message).toBe( + "Access denied", + ); + + lines = [url]; + expect((yield* (yield* signIn).waitForCompletion.pipe(Effect.flip)).message).toContain( + "did not finish signing in to 'figma'", + ); + + lines = [encode({ error: { message: "Unknown MCP server 'figma'." } })]; + expect((yield* signIn.pipe(Effect.flip)).message).toBe("Unknown MCP server 'figma'."); + }), + ).pipe(Effect.provide(NodeServices.layer)), + ); +}); diff --git a/apps/server/src/scient/extensions/ScientAgentMcpInventory.ts b/apps/server/src/scient/extensions/ScientAgentMcpInventory.ts index 61481a0cfd..e17d55ee9f 100644 --- a/apps/server/src/scient/extensions/ScientAgentMcpInventory.ts +++ b/apps/server/src/scient/extensions/ScientAgentMcpInventory.ts @@ -2,7 +2,9 @@ import type { ServerProviderMcpServer } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; +import * as Queue from "effect/Queue"; import * as Schema from "effect/Schema"; +import * as Stream from "effect/Stream"; import { readPluginJson } from "./LocalPluginFiles.ts"; const Config = Schema.Struct({ @@ -33,3 +35,132 @@ export const readScientAgentMcpServers = Effect.fn("readScientAgentMcpServers")( }, Effect.mapError(() => ({ message: "Could not read Scient Agent's MCP configuration." })), ); + +const McpListOutput = Schema.Union([ + Schema.Struct({ + servers: Schema.Array( + Schema.Struct({ + name: Schema.String, + status: Schema.Literals(["connected", "needs-auth", "failed", "pending"]), + scope: Schema.optional(Schema.String), + pluginId: Schema.optional(Schema.String), + toolCount: Schema.optional(Schema.Finite), + error: Schema.optional(Schema.String), + canStartSignIn: Schema.optional(Schema.Boolean), + }), + ), + }), + Schema.Struct({ error: Schema.Struct({ message: Schema.String }) }), +]); +const decodeMcpList = Schema.decodeUnknownOption(Schema.fromJsonString(McpListOutput)); + +const nonEmpty = (text: string | undefined) => { + const trimmed = text?.trim(); + return trimmed ? trimmed : undefined; +}; + +/** The servers `scient-agent mcp list` connected, or a failure for an error or unreadable answer. */ +export function scientAgentMcpRows( + stdout: string, +): Effect.Effect, { readonly message: string }> { + const decoded = decodeMcpList(stdout.trim().split("\n").at(-1) ?? ""); + if (decoded._tag === "None") + return Effect.fail({ message: "Scient Agent's MCP server list could not be read." }); + if ("error" in decoded.value) + return Effect.fail({ + message: nonEmpty(decoded.value.error.message) ?? "Scient Agent could not list MCP servers.", + }); + return Effect.succeed( + decoded.value.servers + .slice(0, 1000) + .flatMap((server): ReadonlyArray => { + const name = nonEmpty(server.name); + if (!name) return []; + const pluginId = nonEmpty(server.pluginId); + const scope = nonEmpty(server.scope); + const error = nonEmpty(server.error); + return [ + { + name, + status: server.status, + ...(pluginId ? { pluginId } : {}), + ...(scope ? { scope } : {}), + ...(server.toolCount === undefined + ? {} + : { toolCount: Math.max(0, Math.trunc(server.toolCount)) }), + ...(error ? { error } : {}), + ...(server.canStartSignIn === true ? { canStartSignIn: true } : {}), + }, + ]; + }), + ); +} + +const LoginLine = Schema.Union([ + Schema.Struct({ type: Schema.Literal("authorization_url"), url: Schema.String }), + Schema.Struct({ type: Schema.Literal("completed") }), + Schema.Struct({ type: Schema.Literal("failed"), message: Schema.String }), + Schema.Struct({ error: Schema.Struct({ message: Schema.String }) }), +]); +const decodeLoginLine = Schema.decodeUnknownOption(Schema.fromJsonString(LoginLine)); +type LoginEvent = typeof LoginLine.Type | { readonly type: "exited" }; + +/** The agent's own flow gives up after five minutes; this only catches one that never reports. */ +const SIGN_IN_WAIT = "330 seconds"; +const AUTHORIZATION_URL_WAIT = "90 seconds"; + +/** + * Follows `scient-agent mcp login `: an authorization page, then one terminal line. The + * process holds the browser callback listener, so it lives in the caller's scope until then. + */ +export const scientAgentMcpSignIn = Effect.fn("scientAgentMcpSignIn")(function* ( + lines: Stream.Stream, + serverName: string, +) { + const events = yield* Queue.unbounded(); + yield* lines.pipe( + Stream.runForEach((line) => { + const event = decodeLoginLine(line.trim()); + return event._tag === "Some" ? Queue.offer(events, event.value) : Effect.void; + }), + Effect.exit, + Effect.andThen(Queue.offer(events, { type: "exited" })), + Effect.forkScoped, + ); + const failure = (event: LoginEvent): { readonly message: string } => ({ + message: + ("error" in event + ? nonEmpty(event.error.message) + : event.type === "failed" + ? nonEmpty(event.message) + : undefined) ?? `Scient Agent did not finish signing in to '${serverName}'.`, + }); + const first = yield* Queue.take(events).pipe( + Effect.timeoutOrElse({ + duration: AUTHORIZATION_URL_WAIT, + orElse: () => + Effect.fail({ message: `Scient Agent did not open a sign-in page for '${serverName}'.` }), + }), + ); + if (!("type" in first) || first.type !== "authorization_url") + return yield* Effect.fail(failure(first)); + const waitForCompletion: Effect.Effect = Effect.gen( + function* () { + while (true) { + const event = yield* Queue.take(events); + if ("type" in event && event.type === "completed") return; + if ("type" in event && event.type === "authorization_url") continue; + return yield* Effect.fail(failure(event)); + } + }, + ).pipe( + Effect.timeoutOrElse({ + duration: SIGN_IN_WAIT, + orElse: () => + Effect.fail({ + message: `Scient Agent did not report the sign-in to '${serverName}' finishing in time.`, + }), + }), + ); + return { authorizationUrl: first.url, waitForCompletion }; +}); diff --git a/apps/server/src/scient/extensions/ScientAgentPluginInventory.ts b/apps/server/src/scient/extensions/ScientAgentPluginInventory.ts index b8bd3aae79..9b65886996 100644 --- a/apps/server/src/scient/extensions/ScientAgentPluginInventory.ts +++ b/apps/server/src/scient/extensions/ScientAgentPluginInventory.ts @@ -5,6 +5,7 @@ import * as Effect from "effect/Effect"; import * as Path from "effect/Path"; import * as PubSub from "effect/PubSub"; import * as Ref from "effect/Ref"; +import type * as Scope from "effect/Scope"; import * as Schema from "effect/Schema"; import * as Semaphore from "effect/Semaphore"; import * as Stream from "effect/Stream"; @@ -14,6 +15,7 @@ import type { ProviderNativeInventory, } from "../../provider/ScientProviderInstanceSeams.ts"; import { runScientAgentPluginCommand } from "./ProviderPluginCommand.ts"; +import { scientAgentMcpRows, scientAgentMcpSignIn } from "./ScientAgentMcpInventory.ts"; import { readPluginJson } from "./LocalPluginFiles.ts"; const Installed = Schema.Struct({ @@ -81,6 +83,23 @@ function scientAgentInstalledPlugins( ]; } +const SIGN_IN_ELSEWHERE = "Manage this MCP server's sign-in in Scient Agent."; + +/** The agent's `mcp` host command; each answers `undefined` when this build does not offer it. */ +export interface ScientAgentMcpHost { + readonly list: ( + serverName?: string, + ) => Effect.Effect; + /** Stdout lines of `mcp login `, whose process lives in the caller's scope. */ + readonly login: ( + serverName: string, + ) => Effect.Effect< + Stream.Stream | undefined, + { readonly message: string }, + Scope.Scope + >; +} + const McpFile = Schema.Record(Schema.String, Schema.Unknown); const decodeMcp = Schema.decodeUnknownOption(McpFile); const pluginMcpServers = Effect.fn("pluginMcpServers")(function* ( @@ -122,6 +141,7 @@ export const makeScientAgentPluginInventory = Effect.fn("makeScientAgentPluginIn ReadonlyArray, { readonly message: string } > = () => Effect.succeed([]), + mcp?: ScientAgentMcpHost, ) { const reports = yield* Effect.acquireRelease( PubSub.unbounded({ replay: 1 }), @@ -132,6 +152,7 @@ export const makeScientAgentPluginInventory = Effect.fn("makeScientAgentPluginIn const lock = yield* Semaphore.make(1); const lastRead = yield* Ref.make(undefined); const path = yield* Path.Path; + const scope = yield* Effect.scope; const list = Effect.fn("ScientAgentPluginInventory.list")( function* (cwd: string | undefined) { const sequence = yield* nextInventoryReadSequence; @@ -166,40 +187,87 @@ export const makeScientAgentPluginInventory = Effect.fn("makeScientAgentPluginIn plugin.name, ]); }); + const listAgentMcp = (serverName?: string) => + mcp + ? mcp + .list(serverName) + .pipe( + Effect.flatMap((stdout) => + stdout === undefined ? Effect.undefined : scientAgentMcpRows(stdout), + ), + ) + : Effect.undefined; + const refreshInventory = ({ force }: { readonly force: boolean }) => + lock.withPermits(1)( + Effect.gen(function* () { + const now = yield* Clock.currentTimeMillis; + const previous = yield* Ref.get(lastRead); + if (!force && previous !== undefined && now - previous < 600_000) return; + const [listing, configured, agentServers] = yield* Effect.all( + [ + list(undefined), + standalone(), + // A failed live listing leaves the configured servers in place. + listAgentMcp().pipe(Effect.orElseSucceed(() => undefined)), + ], + { concurrency: "unbounded" }, + ); + const pluginServers = (yield* Effect.forEach(listing.plugins, (plugin) => + pluginMcpServers(plugin).pipe(Effect.provideService(Path.Path, path)), + )).flat(); + const names = new Set(configured.map((server) => server.name)); + const fileServers = [ + ...configured, + ...pluginServers.filter((server) => !names.has(server.name)), + ]; + const agentNames = new Set(agentServers?.map((server) => server.name)); + // The agent names every server it loads; it omits disabled ones, and other live + // sources (ChatGPT apps) report rows it does not. + const mcpServers = agentServers + ? [ + ...agentServers, + ...fileServers.filter( + (server) => !agentNames.has(server.name) && server.status !== "unknown", + ), + ] + : fileServers; + yield* PubSub.publish(reports, { + plugins: listing.plugins, + mcpServers, + sequence: listing.sequence, + }); + yield* Ref.set(lastRead, now); + }), + ); const actions: ProviderPluginActions = { listPlugins: ({ cwd }) => list(cwd), uninstall: (input) => mutate(input, "uninstall"), setEnabled: (input) => mutate(input, input.enabled ? "enable" : "disable"), - readMcpServer: () => Effect.undefined, - startMcpSignIn: () => - Effect.fail({ message: "Manage this MCP server's sign-in in Scient Agent." }), + readMcpServer: ({ serverName }) => + listAgentMcp(serverName).pipe( + Effect.map((rows) => rows?.find((server) => server.name === serverName)), + ), + startMcpSignIn: Effect.fn("ScientAgentPluginInventory.startMcpSignIn")(function* ({ + serverName, + }: { + readonly serverName: string; + }) { + const lines = mcp ? yield* mcp.login(serverName) : undefined; + if (!lines) return yield* Effect.fail({ message: SIGN_IN_ELSEWHERE }); + const attempt = yield* scientAgentMcpSignIn(lines, serverName); + return { + authorizationUrl: attempt.authorizationUrl, + // The agent stores the credential itself; its listing then shows the server connected. + waitForCompletion: attempt.waitForCompletion.pipe( + Effect.tap(() => + refreshInventory({ force: true }).pipe(Effect.ignore, Effect.forkIn(scope)), + ), + ), + }; + }), isRetired: Deferred.isDone(retired), whenRetired: Deferred.await(retired), - refreshInventory: ({ force }) => - lock.withPermits(1)( - Effect.gen(function* () { - const now = yield* Clock.currentTimeMillis; - const previous = yield* Ref.get(lastRead); - if (!force && previous !== undefined && now - previous < 600_000) return; - const [listing, configured] = yield* Effect.all([list(undefined), standalone()], { - concurrency: "unbounded", - }); - const pluginServers = (yield* Effect.forEach(listing.plugins, (plugin) => - pluginMcpServers(plugin).pipe(Effect.provideService(Path.Path, path)), - )).flat(); - const names = new Set(configured.map((server) => server.name)); - const mcpServers = [ - ...configured, - ...pluginServers.filter((server) => !names.has(server.name)), - ]; - yield* PubSub.publish(reports, { - plugins: listing.plugins, - mcpServers, - sequence: listing.sequence, - }); - yield* Ref.set(lastRead, now); - }), - ), + refreshInventory, }; return { actions, reports: Stream.fromPubSub(reports) }; },