Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions apps/server/src/provider/Drivers/ScientAgentDriver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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",
Expand Down
116 changes: 96 additions & 20 deletions apps/server/src/scient/extensions/ProviderPluginCommand.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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<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 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." })),
);
132 changes: 132 additions & 0 deletions apps/server/src/scient/extensions/ScientAgentMcpInventory.test.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -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<string | undefined, { readonly message: string }> =
Effect.succeed(agentList);
const requests: Array<string | undefined> = [];
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<string> = [];
const refreshed = yield* Deferred.make<void>();
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)),
);
});
Loading
Loading