An open-source, faster Devin alternative
TypeScript
Compile MCP servers and sync redirect secret origins (#627)
Mohamed Habibd0e36c16f124
diff --git a/agent/README.md b/agent/README.mdindex 2ceab1af..5929e883 100644--- a/agent/README.md+++ b/agent/README.md@@ -49,6 +49,12 @@ const github = defineConnection({origin: "https://api.github.com",methods: ["GET"],pathPrefix: "/repos/",+ redirectOrigins: [+ {+ origin: "https://codeload.github.com",+ pathPrefix: "/opencomputer/",+ },+ ],headers: {Authorization: bearer(useSecret("GITHUB_TOKEN")),},@@ -72,7 +78,9 @@ export default function Agent() {`defineConnection().fetch()` sends a relative request through OpenComputer'smanaged egress gateway. The gateway checks the deployment, agent, environment,origin, path, and method before resolving and injecting the secret. Redirects-are not followed by the gateway.+are denied unless the connection declares a matching `redirectOrigins` entry.+The gateway follows at most one redirect for `GET` or `HEAD` and never forwards+the original request headers or managed secrets to the redirect destination.Hooks may only be called while the managed runtime is rendering an agent.diff --git a/agent/src/index.ts b/agent/src/index.tsindex d99c1068..d33e7206 100644--- a/agent/src/index.ts+++ b/agent/src/index.ts@@ -1,10 +1,18 @@export type DataValue =- | null | boolean | number | string+ | null+ | boolean+ | number+ | string| readonly DataValue[]| { readonly [key: string]: DataValue };export type InputSource =- | "user" | "channel" | "schedule" | "webhook" | "subagent" | "system";+ | "user"+ | "channel"+ | "schedule"+ | "webhook"+ | "subagent"+ | "system";export interface AgentInput {readonly source: InputSource;@@ -36,9 +44,15 @@ export interface HttpConnectionDefinition extends ConnectionReference {readonly headers: Readonly<Record<string, string | SecretHeaderReference>>;readonly methods?: readonly string[];readonly pathPrefix?: string;+ readonly redirectOrigins?: readonly HttpConnectionRedirectOrigin[];fetch(path: string, init?: RequestInit): Promise<Response>;}+export interface HttpConnectionRedirectOrigin {+ readonly origin: string;+ readonly pathPrefix?: string;+}+export interface McpServerDefinition extends ResourceReference {readonly kind: "mcp";readonly url: string;@@ -57,13 +71,12 @@ export interface ToolExecutionContext {readonly messageId: string;readonly agentId: string;readonly signal?: AbortSignal;- reportProgress(- metadata: Readonly<Record<string, DataValue>>,- ): Promise<void>;+ reportProgress(metadata: Readonly<Record<string, DataValue>>): Promise<void>;}-export interface ToolDefinition<Output extends DataValue = DataValue>- extends ResourceReference {+export interface ToolDefinition<+ Output extends DataValue = DataValue,+> extends ResourceReference {readonly kind: "tool";readonly version: 1;readonly name: string;@@ -87,9 +100,7 @@ function hooks(): AgentHooks {Symbol.for("opencomputer.agent-hooks")];if (!value) {- throw new Error(- "OpenComputer hooks can only run while rendering an agent",- );+ throw new Error("OpenComputer hooks can only run while rendering an agent");}return value as AgentHooks;}@@ -127,6 +138,7 @@ export function defineConnection(input: {headers?: Readonly<Record<string, string | SecretHeaderReference>>;methods?: readonly string[];pathPrefix?: string;+ redirectOrigins?: readonly HttpConnectionRedirectOrigin[];}): HttpConnectionDefinition {const id = identifier(input.id, "defineConnection");const origin = new URL(input.origin);@@ -135,23 +147,62 @@ export function defineConnection(input: {}for (const [name, value] of Object.entries(input.headers ?? {})) {if (- ["api-key", "authorization", "cookie", "proxy-authorization", "x-api-key"].includes(- name.toLowerCase(),- ) &&+ [+ "api-key",+ "authorization",+ "cookie",+ "proxy-authorization",+ "x-api-key",+ ].includes(name.toLowerCase()) &&typeof value === "string") {throw new Error(`${name} must use useSecret()`);}}+ if ((input.redirectOrigins?.length ?? 0) > 16) {+ throw new Error("Connections may declare at most 16 redirect origins");+ }+ const redirectOrigins = input.redirectOrigins?.map((input) => {+ const redirectOrigin = new URL(input.origin);+ if (redirectOrigin.protocol !== "https:" || redirectOrigin.pathname !== "/") {+ throw new Error(+ "Connection redirect origins must be HTTPS origins without a path",+ );+ }+ if (input.pathPrefix !== undefined && !input.pathPrefix.startsWith("/")) {+ throw new Error("Connection redirect path prefixes must start with /");+ }+ return Object.freeze({+ origin: redirectOrigin.origin,+ ...(input.pathPrefix ? { pathPrefix: input.pathPrefix } : {}),+ });+ });+ if (+ redirectOrigins &&+ new Set(+ redirectOrigins.map(+ ({ origin, pathPrefix }) => `${origin}\n${pathPrefix ?? ""}`,+ ),+ ).size !== redirectOrigins.length+ ) {+ throw new Error("Connection redirect origin policies must be unique");+ }const definition = {kind: "connection" as const,id,origin: origin.origin,headers: Object.freeze({ ...(input.headers ?? {}) }),...(input.methods- ? { methods: Object.freeze(input.methods.map((method) => method.toUpperCase())) }+ ? {+ methods: Object.freeze(+ input.methods.map((method) => method.toUpperCase()),+ ),+ }: {}),...(input.pathPrefix ? { pathPrefix: input.pathPrefix } : {}),+ ...(redirectOrigins+ ? { redirectOrigins: Object.freeze(redirectOrigins) }+ : {}),async fetch(path: string, init: RequestInit = {}): Promise<Response> {const runtime = globalThis as typeof globalThis & {process?: { env?: Record<string, string | undefined> };@@ -176,7 +227,9 @@ export function defineConnection(input: {);})();if (body !== undefined && body.length > 5 * 1024 * 1024) {- throw new Error("Managed connection request bodies cannot exceed 5 MiB");+ throw new Error(+ "Managed connection request bodies cannot exceed 5 MiB",+ );}return fetch(`${base.replace(/\/$/, "")}/${encodeURIComponent(id)}/fetch`,@@ -250,10 +303,16 @@ export function defineTool<Output extends DataValue = DataValue>(input: {export const useInput = (): Readonly<AgentInput> => hooks().useInput();export const useCurrentInput = useInput;-export const useModel = (model: ModelSelection): void => hooks().useModel(model);-export const useTool = (tool: string | ResourceReference): void => hooks().useTool(tool);-export const useSubagent = (agent: string | ResourceReference): void => hooks().useSubagent(agent);-export const useMcpServer = (server: string | ResourceReference): void => hooks().useMcpServer(server);-export function useSessionData<T extends DataValue>(key: string): T | undefined {+export const useModel = (model: ModelSelection): void =>+ hooks().useModel(model);+export const useTool = (tool: string | ResourceReference): void =>+ hooks().useTool(tool);+export const useSubagent = (agent: string | ResourceReference): void =>+ hooks().useSubagent(agent);+export const useMcpServer = (server: string | ResourceReference): void =>+ hooks().useMcpServer(server);+export function useSessionData<T extends DataValue>(+ key: string,+): T | undefined {return hooks().useSessionData<T>(key);}diff --git a/cli/src/api.ts b/cli/src/api.tsindex bbfd64c5..61135164 100644--- a/cli/src/api.ts+++ b/cli/src/api.ts@@ -288,15 +288,17 @@ export class OpenComputerClient {origin: string;headers: Record<string,- string | {- kind: "secret";- name: string;- prefix?: string;- suffix?: string;- }+ | string+ | {+ kind: "secret";+ name: string;+ prefix?: string;+ suffix?: string;+ }>;methods?: string[];pathPrefix?: string;+ redirectOrigins?: Array<{ origin: string; pathPrefix?: string }>;}>;source: {digest: string;diff --git a/cli/src/commands.ts b/cli/src/commands.tsindex 8de7676b..4cfb8b26 100644--- a/cli/src/commands.ts+++ b/cli/src/commands.ts@@ -640,7 +640,12 @@ export async function runCommand((value) => typeof value !== "string" && value.name === name,),)- .map((connection) => connection.origin);+ .flatMap((connection) => [+ connection.origin,+ ...(connection.redirectOrigins ?? []).map(+ (redirect) => redirect.origin,+ ),+ ]);}allowedOrigins = [...new Set(allowedOrigins)];if (!allowedOrigins.length) {diff --git a/cli/src/dev.test.ts b/cli/src/dev.test.tsindex 057af379..58f2653e 100644--- a/cli/src/dev.test.ts+++ b/cli/src/dev.test.ts@@ -141,6 +141,7 @@ test("development syncs declared .env.local secrets to inferred origins", asyncconst github = defineConnection({id: "github-api",origin: "https://api.github.com",+ redirectOrigins: [{ origin: "https://codeload.github.com" }],headers: { Authorization: bearer(useSecret("GITHUB_TOKEN")) },});@@ -230,7 +231,10 @@ export default function Agent() { useTool(repository); return "Use GitHub."; }name: "GITHUB_TOKEN",value: "first-secret",environment: "development",- allowedOrigins: ["https://api.github.com"],+ allowedOrigins: [+ "https://api.github.com",+ "https://codeload.github.com",+ ],},]);await syncDevelopmentSecrets(diff --git a/cli/src/dev.ts b/cli/src/dev.tsindex 21f195ab..5797e8fb 100644--- a/cli/src/dev.ts+++ b/cli/src/dev.ts@@ -72,6 +72,9 @@ function secretOrigins(results: DevelopmentResults): Map<string, string[]> {if (typeof header === "string") continue;const current = origins.get(header.name) ?? new Set<string>();current.add(connection.origin);+ for (const redirect of connection.redirectOrigins ?? []) {+ current.add(redirect.origin);+ }origins.set(header.name, current);}}diff --git a/cli/src/project.test.ts b/cli/src/project.test.tsindex a1291175..4bd2c1b0 100644--- a/cli/src/project.test.ts+++ b/cli/src/project.test.ts@@ -203,6 +203,11 @@ export default function Agent() {connections: string[];httpConnections: unknown[];mcpServers: string[];+ mcpServerDefinitions: Array<{+ id: string;+ url: string;+ connection?: string;+ }>;};assert.deepEqual(manifest, {version: 2,@@ -213,6 +218,9 @@ export default function Agent() {connections: [],httpConnections: [],mcpServers: ["docs"],+ mcpServerDefinitions: [+ { id: "docs", url: "https://mcp.example.com/" },+ ],});await assert.rejects(stat(resolve(initialized.agentRoot, "opencomputer.toml")),@@ -237,6 +245,12 @@ export const github = defineConnection({origin: "https://api.github.com",methods: ["GET"],pathPrefix: "/repos/",+ redirectOrigins: [+ {+ origin: "https://codeload.github.com",+ pathPrefix: "/opencomputer/example/",+ },+ ],headers: { Authorization: bearer(useSecret("GITHUB_TOKEN")) },});@@ -274,6 +288,12 @@ export default function Agent() {origin: "https://api.github.com",methods: ["GET"],pathPrefix: "/repos/",+ redirectOrigins: [+ {+ origin: "https://codeload.github.com",+ pathPrefix: "/opencomputer/example/",+ },+ ],headers: {Authorization: {kind: "secret",@@ -290,6 +310,48 @@ export default function Agent() {}});+test("the compiler records managed MCP server definitions", async () => {+ const parent = await mkdtemp(resolve(tmpdir(), "opencomputer-mcp-"));+ const root = resolve(parent, "app");+ try {+ const initialized = await initializeAgentProject(root);+ await writeFile(+ resolve(initialized.agentRoot, "agent.ts"),+ `import { bearer, defineConnection, defineMcpServer, useMcpServer, useSecret } from "@opencomputer/agent";++const unleash = defineConnection({+ id: "unleash-api",+ origin: "https://example.getunleash.io",+ pathPrefix: "/api/admin/mcp",+ headers: { Authorization: bearer(useSecret("UNLEASH_TOKEN")) },+});+const server = defineMcpServer({+ id: "unleash",+ url: "https://example.getunleash.io/api/admin/mcp",+ connection: unleash,+});+export default function Agent() {+ useMcpServer(server);+ return "Use Unleash.";+}+`,+ );+ const runtime = await prepareAgent(initialized.agentRoot);+ const manifest = JSON.parse(+ await readFile(resolve(runtime, ".opencomputer", "reactive.json"), "utf8"),+ ) as { mcpServerDefinitions: unknown[] };+ assert.deepEqual(manifest.mcpServerDefinitions, [+ {+ id: "unleash",+ url: "https://example.getunleash.io/api/admin/mcp",+ connection: "unleash-api",+ },+ ]);+ } finally {+ await rm(parent, { recursive: true, force: true });+ }+});+test("the compiler rejects hard-coded sensitive connection headers", async () => {const parent = await mkdtemp(resolve(tmpdir(), "opencomputer-egress-secret-"),diff --git a/cli/src/project.ts b/cli/src/project.tsindex cd52436b..89534d45 100644--- a/cli/src/project.ts+++ b/cli/src/project.ts@@ -37,6 +37,13 @@ export interface HttpConnectionManifest {>;methods?: string[];pathPrefix?: string;+ redirectOrigins?: Array<{ origin: string; pathPrefix?: string }>;+}++export interface McpServerManifest {+ id: string;+ url: string;+ connection?: string;}export interface ProjectAgentSource {@@ -667,14 +674,106 @@ function literalHookIds(source: string, hook: string): string[] {return [...source.matchAll(pattern)].map((match) => match[1]!).sort();}-function definedMcpServerIds(source: string): string[] {- return [- ...source.matchAll(- /\bdefineMcpServer\s*\(\s*\{[\s\S]*?\bid\s*:\s*["']([^"']+)["'][\s\S]*?\}\s*\)/g,- ),- ]- .map((match) => match[1]!)- .sort();+function definedConnectionBindings(+ source: string,+ path: string,+): Map<string, HttpConnectionManifest> {+ const file = ts.createSourceFile(path, source, ts.ScriptTarget.Latest, true);+ const definitions = new Map(+ definedHttpConnections(source, path).map((definition) => [+ definition.id,+ definition,+ ]),+ );+ const bindings = new Map<string, HttpConnectionManifest>();+ const visit = (node: ts.Node): void => {+ if (+ ts.isVariableDeclaration(node) &&+ ts.isIdentifier(node.name) &&+ node.initializer &&+ ts.isCallExpression(node.initializer) &&+ ts.isIdentifier(node.initializer.expression) &&+ node.initializer.expression.text === "defineConnection"+ ) {+ const input = node.initializer.arguments[0];+ if (input && ts.isObjectLiteralExpression(input)) {+ const id = literalStringValue(+ objectProperty(input, "id"),+ "connection id",+ );+ const definition = definitions.get(id);+ if (definition) bindings.set(node.name.text, definition);+ }+ }+ ts.forEachChild(node, visit);+ };+ visit(file);+ return bindings;+}++function definedMcpServers(+ source: string,+ path: string,+ connectionBindings: ReadonlyMap<string, HttpConnectionManifest>,+): McpServerManifest[] {+ const file = ts.createSourceFile(path, source, ts.ScriptTarget.Latest, true);+ const definitions: McpServerManifest[] = [];+ const visit = (node: ts.Node): void => {+ if (+ ts.isCallExpression(node) &&+ ts.isIdentifier(node.expression) &&+ node.expression.text === "defineMcpServer"+ ) {+ const input = node.arguments[0];+ if (!input || !ts.isObjectLiteralExpression(input)) {+ throw new Error("defineMcpServer() requires an object literal");+ }+ const id = literalStringValue(+ objectProperty(input, "id"),+ "MCP server id",+ );+ const value = literalStringValue(+ objectProperty(input, "url"),+ `MCP server ${id} URL`,+ );+ const url = new URL(value);+ if (url.protocol !== "https:") {+ throw new Error(`MCP server ${id} must use HTTPS`);+ }+ const connectionExpression = objectProperty(input, "connection");+ let connection: HttpConnectionManifest | undefined;+ if (connectionExpression) {+ if (!ts.isIdentifier(connectionExpression)) {+ throw new Error(+ `MCP server ${id} connection must reference a defineConnection() binding`,+ );+ }+ connection = connectionBindings.get(connectionExpression.text);+ if (!connection) {+ throw new Error(+ `MCP server ${id} references unknown connection ${connectionExpression.text}`,+ );+ }+ if (+ url.origin !== connection.origin ||+ (connection.pathPrefix &&+ !url.pathname.startsWith(connection.pathPrefix))+ ) {+ throw new Error(+ `MCP server ${id} URL is outside connection ${connection.id}`,+ );+ }+ }+ definitions.push({+ id,+ url: url.toString(),+ ...(connection ? { connection: connection.id } : {}),+ });+ }+ ts.forEachChild(node, visit);+ };+ visit(file);+ return definitions.sort((left, right) => left.id.localeCompare(right.id));}function objectProperty(@@ -844,6 +943,68 @@ function definedHttpConnections(`connection ${id} pathPrefix`,);}+ const redirectOrigins = objectProperty(input, "redirectOrigins");+ if (redirectOrigins) {+ if (!ts.isArrayLiteralExpression(redirectOrigins)) {+ throw new Error(+ `Connection ${id} redirectOrigins must be an array literal`,+ );+ }+ if (redirectOrigins.elements.length > 16) {+ throw new Error(+ `Connection ${id} may declare at most 16 redirect origins`,+ );+ }+ const policies = new Set<string>();+ definition.redirectOrigins = redirectOrigins.elements.map(+ (element, index) => {+ if (!ts.isObjectLiteralExpression(element)) {+ throw new Error(+ `Connection ${id} redirect origin ${index} must be an object literal`,+ );+ }+ const value = literalStringValue(+ objectProperty(element, "origin"),+ `connection ${id} redirect origin ${index}`,+ );+ const redirectOrigin = new URL(value);+ if (+ redirectOrigin.protocol !== "https:" ||+ redirectOrigin.pathname !== "/"+ ) {+ throw new Error(+ `Connection ${id} redirect origin ${index} must be an HTTPS origin without a path`,+ );+ }+ const redirectPathPrefix = objectProperty(element, "pathPrefix");+ const parsedPathPrefix = redirectPathPrefix+ ? literalStringValue(+ redirectPathPrefix,+ `connection ${id} redirect origin ${index} pathPrefix`,+ )+ : undefined;+ if (+ parsedPathPrefix !== undefined &&+ !parsedPathPrefix.startsWith("/")+ ) {+ throw new Error(+ `Connection ${id} redirect origin ${index} pathPrefix must start with /`,+ );+ }+ const policyKey = `${redirectOrigin.origin}\n${parsedPathPrefix ?? ""}`;+ if (policies.has(policyKey)) {+ throw new Error(+ `Connection ${id} redirect origin policies must be unique`,+ );+ }+ policies.add(policyKey);+ return {+ origin: redirectOrigin.origin,+ ...(parsedPathPrefix ? { pathPrefix: parsedPathPrefix } : {}),+ };+ },+ );+ }definitions.push(definition);}ts.forEachChild(node, visit);@@ -887,12 +1048,21 @@ export const defineConnection = (input) => {for (const [name, value] of Object.entries(input.headers || {})) {if (["api-key", "authorization", "cookie", "proxy-authorization", "x-api-key"].includes(name.toLowerCase()) && typeof value === "string") throw new Error(name + " must use useSecret()");}+ const redirectOrigins = (input.redirectOrigins || []).map((input) => {+ const redirectOrigin = new URL(input.origin);+ if (redirectOrigin.protocol !== "https:" || redirectOrigin.pathname !== "/") throw new Error("Connection redirect origins must be HTTPS origins without a path");+ if (input.pathPrefix != null && !input.pathPrefix.startsWith("/")) throw new Error("Connection redirect path prefixes must start with /");+ return Object.freeze({ origin: redirectOrigin.origin, ...(input.pathPrefix ? { pathPrefix: input.pathPrefix } : {}) });+ });+ if (redirectOrigins.length > 16) throw new Error("Connections may declare at most 16 redirect origins");+ if (new Set(redirectOrigins.map(({ origin, pathPrefix }) => origin + "\\n" + (pathPrefix || ""))).size !== redirectOrigins.length) throw new Error("Connection redirect origin policies must be unique");return Object.freeze({kind: "connection",...input,id: connectionId,origin: origin.origin,headers: Object.freeze({ ...(input.headers || {}) }),+ ...(redirectOrigins.length ? { redirectOrigins: Object.freeze(redirectOrigins) } : {}),async fetch(path, init = {}) {const base = globalThis.process?.env?.OPENCOMPUTER_CONNECTIONS_URL;const token = globalThis.process?.env?.OPENCOMPUTER_CONNECTION_TOKEN;@@ -1131,6 +1301,42 @@ the product or support surface presented to users.`Connection id ${JSON.stringify(duplicateConnection.id)} is defined more than once`,);}+ const connectionBindings = new Map<string, HttpConnectionManifest>();+ for (const [index, source] of [+ agentSource,+ ...toolSources.map((item) => item.source),+ ].entries()) {+ const filename =+ index === 0 ? "agent.ts" : toolSources[index - 1]!.filename;+ for (const [name, definition] of definedConnectionBindings(+ source,+ filename,+ )) {+ const existing = connectionBindings.get(name);+ if (existing && existing.id !== definition.id) {+ throw new Error(+ `Connection binding ${JSON.stringify(name)} is defined more than once`,+ );+ }+ connectionBindings.set(name, definition);+ }+ }+ const mcpServerDefinitions = definedMcpServers(+ agentSource,+ "agent.ts",+ connectionBindings,+ );+ const duplicateMcpServer = mcpServerDefinitions.find(+ (server, index) =>+ mcpServerDefinitions.findIndex(+ (candidate) => candidate.id === server.id,+ ) !== index,+ );+ if (duplicateMcpServer) {+ throw new Error(+ `MCP server id ${JSON.stringify(duplicateMcpServer.id)} is defined more than once`,+ );+ }await mkdir(resolve(runtime, ".opencomputer"), { recursive: true });await writeFile(resolve(runtime, ".opencomputer", "reactive.json"),@@ -1150,10 +1356,11 @@ the product or support surface presented to users.httpConnections,mcpServers: [...new Set([- ...definedMcpServerIds(agentSource),+ ...mcpServerDefinitions.map((server) => server.id),...literalHookIds(agentSource, "useMcpServer"),]),].sort(),+ mcpServerDefinitions,},null,2,