Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 68e0505d9f |
@@ -96,7 +96,10 @@ The workflow:
|
||||
|
||||
### APIs Connected
|
||||
|
||||
The server connects to the Molecule AI platform REST API. See the platform SDK (`../molecule-sdk-python`) for the underlying API client used.
|
||||
The server connects to the Molecule AI platform REST API via its own TypeScript
|
||||
client (`src/api.ts`). It does not use the Python SDK (`molecule-sdk-python`) —
|
||||
the Python SDK is for remote agents that run outside the platform; this server
|
||||
runs as an MCP bridge *on* the operator side.
|
||||
|
||||
### Environment Variables
|
||||
|
||||
@@ -110,7 +113,7 @@ For local development, copy `.env.example` → `.env` and fill in values.
|
||||
|
||||
### Postgres
|
||||
|
||||
Platform data lives in Postgres (source of truth). The server reads data via the platform SDK — it does not connect to Postgres directly.
|
||||
Platform data lives in Postgres (source of truth). The server reads data via the platform REST API — it does not connect to Postgres directly.
|
||||
|
||||
## TypeScript Conventions
|
||||
|
||||
|
||||
-24
@@ -45,24 +45,16 @@ export function toMcpText(text: string) {
|
||||
return { content: [{ type: "text" as const, text }] };
|
||||
}
|
||||
|
||||
// Default per-request timeout for all API calls (30 s). Covers the 99th-percentile
|
||||
// platform response under normal load; long-running operations (bundle export,
|
||||
// agent chat) should pass a larger timeout via the caller's context.
|
||||
const DEFAULT_TIMEOUT_MS = 30_000;
|
||||
|
||||
export async function apiCall<T = unknown>(
|
||||
method: string,
|
||||
path: string,
|
||||
body?: unknown,
|
||||
timeoutMs?: number,
|
||||
): Promise<T | ApiError> {
|
||||
const timeout = timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
||||
try {
|
||||
const res = await fetch(`${PLATFORM_URL}${path}`, {
|
||||
method,
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: body ? JSON.stringify(body) : undefined,
|
||||
signal: AbortSignal.timeout(timeout),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const text = await res.text();
|
||||
@@ -76,12 +68,7 @@ export async function apiCall<T = unknown>(
|
||||
}
|
||||
} catch (err) {
|
||||
const msg = err instanceof Error ? err.message : String(err);
|
||||
const isTimeout =
|
||||
err instanceof Error && (err.name === "TimeoutError" || msg.includes("timed out"));
|
||||
logError(err, `Molecule AI API error (${method} ${path})`, { platformUrl: PLATFORM_URL });
|
||||
if (isTimeout) {
|
||||
return { error: `Request timed out after ${timeout} ms (${method} ${path})`, detail: msg };
|
||||
}
|
||||
return { error: `Platform unreachable at ${PLATFORM_URL}`, detail: msg };
|
||||
}
|
||||
}
|
||||
@@ -101,9 +88,7 @@ export async function apiCall<T = unknown>(
|
||||
export async function platformGet<T = unknown>(
|
||||
path: string,
|
||||
maxRetries = 3,
|
||||
timeoutMs?: number,
|
||||
): Promise<T | ApiError> {
|
||||
const timeout = timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
||||
let attempt = 0;
|
||||
|
||||
while (true) {
|
||||
@@ -111,7 +96,6 @@ export async function platformGet<T = unknown>(
|
||||
const res = await fetch(`${PLATFORM_URL}${path}`, {
|
||||
method: "GET",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
signal: AbortSignal.timeout(timeout),
|
||||
});
|
||||
|
||||
if (res.status === 429 && attempt < maxRetries) {
|
||||
@@ -153,15 +137,7 @@ export async function platformGet<T = unknown>(
|
||||
}
|
||||
} catch (err) {
|
||||
const msg = err instanceof Error ? err.message : String(err);
|
||||
const isTimeout =
|
||||
err instanceof Error && (err.name === "TimeoutError" || msg.includes("timed out"));
|
||||
logError(err, `Molecule AI API error (GET ${path})`, { platformUrl: PLATFORM_URL });
|
||||
if (isTimeout) {
|
||||
return {
|
||||
error: `Request timed out after ${timeout} ms (GET ${path})`,
|
||||
detail: msg,
|
||||
};
|
||||
}
|
||||
return { error: `Platform unreachable at ${PLATFORM_URL}`, detail: msg };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -48,8 +48,6 @@ export type GetModelParams = z.infer<typeof GetModelSchema>;
|
||||
|
||||
export async function handleChatWithAgent(args: unknown): Promise<ReturnType<typeof toMcpResult>> {
|
||||
const params = validate(args, ChatWithAgentSchema);
|
||||
// Agent chat can involve multi-turn LLM inference — allow up to 2 min rather
|
||||
// than the 30 s default so complex tasks don't time out mid-generation.
|
||||
const data = await apiCall<
|
||||
{ result?: { parts?: Array<{ kind?: string; text?: string }> } }
|
||||
>(
|
||||
@@ -61,7 +59,6 @@ export async function handleChatWithAgent(args: unknown): Promise<ReturnType<typ
|
||||
message: { role: "user", parts: [{ type: "text", text: params.message }] },
|
||||
},
|
||||
},
|
||||
120_000, // 2-minute timeout for agent chat
|
||||
);
|
||||
const parts =
|
||||
(data as { result?: { parts?: Array<{ kind?: string; text?: string }> } } | null)?.result?.parts || [];
|
||||
|
||||
@@ -8,9 +8,7 @@ export async function handleAsyncDelegate(params: {
|
||||
task: string;
|
||||
}) {
|
||||
const { workspace_id, target_id, task } = params;
|
||||
// Delegation can trigger multi-step agent chains — use a 5-minute timeout to avoid
|
||||
// premature failures on complex cross-workspace workflows.
|
||||
const data = await apiCall("POST", `/workspaces/${workspace_id}/delegate`, { target_id, task }, 300_000);
|
||||
const data = await apiCall("POST", `/workspaces/${workspace_id}/delegate`, { target_id, task });
|
||||
return toMcpResult(data);
|
||||
}
|
||||
|
||||
|
||||
@@ -150,25 +150,6 @@ describe("apiCall", () => {
|
||||
expect((result as { detail: string }).detail).toContain("Failed to fetch");
|
||||
});
|
||||
|
||||
it("returns ApiError with timeout message when request times out", async () => {
|
||||
// Simulate what AbortSignal.timeout() fires when its timer expires:
|
||||
// the error's .name is "TimeoutError" and .message contains "timed out".
|
||||
// Using a plain Error with name set to "TimeoutError" so the instanceof
|
||||
// Error check in apiCall's catch block succeeds and detects it as a timeout.
|
||||
const timeoutError = Object.assign(new Error("The operation was aborted due to timeout."), {
|
||||
name: "TimeoutError",
|
||||
});
|
||||
global.fetch = jest.fn().mockRejectedValue(timeoutError);
|
||||
|
||||
const result = await apiCall("GET", "/workspaces");
|
||||
|
||||
expect(isApiError(result)).toBe(true);
|
||||
// Timeout errors are surfaced distinctly from network-unreachable errors.
|
||||
// The error field includes the timeout summary; the detail is the raw message.
|
||||
expect((result as { error: string }).error).toContain("timed out");
|
||||
expect((result as { detail: string }).detail).toBeTruthy();
|
||||
});
|
||||
|
||||
it("sends JSON body on POST with body argument", async () => {
|
||||
global.fetch = mockFetch({ id: "ws-new" }, { status: 201 });
|
||||
|
||||
@@ -202,17 +183,6 @@ describe("apiCall", () => {
|
||||
const call = (fetch as jest.Mock).mock.calls[0];
|
||||
expect(call[1].headers).toEqual({ "Content-Type": "application/json" });
|
||||
});
|
||||
|
||||
it("passes custom timeoutMs to AbortSignal.timeout()", async () => {
|
||||
global.fetch = mockFetch({ id: "ws-1" }, { status: 200 });
|
||||
|
||||
await apiCall("GET", "/workspaces/ws-1", undefined, 5_000);
|
||||
|
||||
const call = (fetch as jest.Mock).mock.calls[0];
|
||||
expect(call[1].signal).toBeDefined();
|
||||
// Verify the signal is an AbortSignal instance
|
||||
expect(call[1].signal instanceof AbortSignal).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -252,20 +222,6 @@ describe("platformGet", () => {
|
||||
expect((result as { error: string }).error).toContain("Platform unreachable");
|
||||
});
|
||||
|
||||
it("returns ApiError with timeout message when request times out", async () => {
|
||||
// Simulate what AbortSignal.timeout() fires when its timer expires.
|
||||
const timeoutError = Object.assign(new Error("The operation was aborted due to timeout."), {
|
||||
name: "TimeoutError",
|
||||
});
|
||||
global.fetch = jest.fn().mockRejectedValue(timeoutError);
|
||||
|
||||
const result = await platformGet("/workspaces");
|
||||
|
||||
expect(isApiError(result)).toBe(true);
|
||||
expect((result as { error: string }).error).toContain("timed out");
|
||||
expect((result as { detail: string }).detail).toBeTruthy();
|
||||
});
|
||||
|
||||
describe("429 retry logic", () => {
|
||||
beforeEach(() => {
|
||||
jest.useFakeTimers();
|
||||
|
||||
Reference in New Issue
Block a user