Compare commits
19 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 6cf1c7f3a1 | |||
| 56ad95acdd | |||
| 7d3a67ee56 | |||
| d86fc82014 | |||
| 0ce17a6938 | |||
| 1b0ff4e780 | |||
| 8b8f1b4387 | |||
| d9e3f1d191 | |||
| e2505de394 | |||
| 3cae41253d | |||
| bf6f68a3b8 | |||
| 996a9f6230 | |||
| 4272978ad2 | |||
| 85b6b1e115 | |||
| c6068b2b9f | |||
| 717abd19d1 | |||
| 708535b798 | |||
| e17a54b7b6 | |||
| 9de811596d |
@@ -145,89 +145,142 @@ src/
|
||||
|
||||
## MCP Tool Registry
|
||||
|
||||
Full list of tools exposed by this server. Each is implemented in `src/tools/<name>.ts`.
|
||||
Full list of tools exposed by this server (87 total). Each is implemented in `src/tools/<name>.ts`.
|
||||
|
||||
### Workspace Tools
|
||||
### Workspace Tools (8)
|
||||
| Tool | Description |
|
||||
|------|-------------|
|
||||
| `list_workspaces` | List all workspaces accessible to the authenticated user |
|
||||
| `create_workspace` | Create a new workspace with name, role, tier, and template |
|
||||
| `get_workspace` | Get workspace details by ID |
|
||||
| `update_workspace` | Patch workspace fields (name, tier, parent_id, etc.) |
|
||||
| `list_workspaces` | List all workspaces with their status, skills, and hierarchy |
|
||||
| `create_workspace` | Create a new workspace node on the canvas |
|
||||
| `get_workspace` | Get detailed information about a specific workspace |
|
||||
| `update_workspace` | Update workspace fields (name, role, tier, parent_id, position) |
|
||||
| `delete_workspace` | Delete a workspace (cascades to children) |
|
||||
| `restart_workspace` | Restart all agents in a workspace (picks up new secrets/prompts) |
|
||||
| `restart_workspace` | Restart an offline or failed workspace |
|
||||
| `pause_workspace` | Pause a workspace (stops container, preserves config) |
|
||||
| `resume_workspace` | Resume a paused workspace |
|
||||
|
||||
### Agent Tools
|
||||
### Agent Tools (6)
|
||||
| Tool | Description |
|
||||
|------|-------------|
|
||||
| `list_agents` | List agents in a workspace |
|
||||
| `get_agent` | Get agent details by ID |
|
||||
| `send_message` | Send an A2A message to an agent (returns structured response) |
|
||||
| `list_peers` | List peer agents discoverable by a given agent |
|
||||
| `chat_with_agent` | Send a message to a workspace agent and get a response |
|
||||
| `assign_agent` | Assign an AI model to a workspace |
|
||||
| `replace_agent` | Replace the model on an existing workspace agent |
|
||||
| `remove_agent` | Remove the agent from a workspace |
|
||||
| `move_agent` | Move an agent from one workspace to another |
|
||||
| `get_model` | Get current model configuration for a workspace |
|
||||
|
||||
### Delegation Tools
|
||||
### Delegation Tools (8)
|
||||
| Tool | Description |
|
||||
|------|-------------|
|
||||
| `delegate_task` | Delegate a task to a child workspace (sync, waits for response) |
|
||||
| `delegate_task_async` | Delegate a task to a child workspace (fire-and-forget, returns task_id) |
|
||||
| `async_delegate` | Delegate a task to another workspace (non-blocking, returns delegation_id) |
|
||||
| `check_delegations` | Check status of delegated tasks for a workspace |
|
||||
| `record_delegation` | Register an agent-initiated delegation with the activity log |
|
||||
| `update_delegation_status` | Mirror delegation status to activity_logs (completed or failed) |
|
||||
| `report_activity` | Write an arbitrary activity log row from an agent |
|
||||
| `list_activity` | List activity logs for a workspace (A2A, tasks, errors) |
|
||||
| `notify_user` | Push a notification from the agent to the canvas via WebSocket |
|
||||
| `list_traces` | List recent LLM traces from Langfuse for a workspace |
|
||||
|
||||
### Secrets Tools
|
||||
### Secrets Tools (6)
|
||||
| Tool | Description |
|
||||
|------|-------------|
|
||||
| `get_secret` | Retrieve a secret value for a workspace |
|
||||
| `set_secret` | Set a key/value secret for a workspace |
|
||||
| `delete_secret` | Delete a secret |
|
||||
| `set_secret` | Set an API key or environment variable for a workspace |
|
||||
| `list_secrets` | List secret keys for a workspace (values never exposed) |
|
||||
| `delete_secret` | Delete a secret from a workspace |
|
||||
| `list_global_secrets` | List global secret keys (values never exposed) |
|
||||
| `set_global_secret` | Set a global secret (available to all workspaces) |
|
||||
| `delete_global_secret` | Delete a global secret |
|
||||
|
||||
### Files Tools
|
||||
### Files Tools (7)
|
||||
| Tool | Description |
|
||||
|------|-------------|
|
||||
| `list_files` | List files in a workspace container |
|
||||
| `get_file` | Read a file's content |
|
||||
| `put_file` | Write or update a file in the container |
|
||||
| `delete_file` | Delete a file |
|
||||
| `list_files` | List workspace config files (skills, prompts, config.yaml) |
|
||||
| `read_file` | Read a workspace config file |
|
||||
| `write_file` | Write or create a workspace config file |
|
||||
| `delete_file` | Delete a workspace file or folder |
|
||||
| `replace_all_files` | Replace all workspace config files at once |
|
||||
| `get_config` | Get workspace runtime config as JSON |
|
||||
| `update_config` | Update workspace runtime config |
|
||||
|
||||
### Memory Tools
|
||||
### Memory Tools (9)
|
||||
| Tool | Description |
|
||||
|------|-------------|
|
||||
| `commit_memory` | Commit a structured memory entry (with optional namespace) |
|
||||
| `recall_memory` | Search previously committed memories |
|
||||
| `commit_memory` | Store a fact in workspace memory (LOCAL, TEAM, or GLOBAL scope) |
|
||||
| `search_memory` | Search workspace memories |
|
||||
| `delete_memory` | Delete a specific memory entry |
|
||||
| `session_search` | Search recent session activity and memory (FTS) |
|
||||
| `get_shared_context` | Get the shared-context blob for a workspace |
|
||||
| `memory_set` | Set a key-value memory entry with optional TTL |
|
||||
| `memory_get` | Read a single K/V memory entry |
|
||||
| `memory_list` | List all K/V memory entries for a workspace |
|
||||
| `memory_delete_kv` | Delete a single K/V memory entry |
|
||||
|
||||
### Plugins Tools
|
||||
### Plugins Tools (7)
|
||||
| Tool | Description |
|
||||
|------|-------------|
|
||||
| `install_plugin` | Download and install a plugin into a workspace from the registry |
|
||||
| `list_plugin_registry` | List all available plugins from the registry |
|
||||
| `list_installed_plugins` | List plugins installed in a workspace |
|
||||
| `install_plugin` | Install a plugin into a workspace (auto-restarts) |
|
||||
| `uninstall_plugin` | Remove a plugin from a workspace (auto-restarts) |
|
||||
| `list_plugin_sources` | List registered plugin install-source schemes |
|
||||
| `list_available_plugins` | List plugins from registry filtered by workspace runtime |
|
||||
| `check_plugin_compatibility` | Preflight: which installed plugins would break if runtime changed? |
|
||||
|
||||
### Channels Tools
|
||||
### Channels Tools (8)
|
||||
| Tool | Description |
|
||||
|------|-------------|
|
||||
| `list_channels` | List communication channels |
|
||||
| `get_channel` | Get channel details |
|
||||
| `post_message` | Post a message to a channel |
|
||||
| `list_channel_adapters` | List available social channel adapters (Telegram, Slack, etc.) |
|
||||
| `list_channels` | List social channels connected to a workspace |
|
||||
| `add_channel` | Connect a social channel to a workspace |
|
||||
| `update_channel` | Update a channel's config, enabled state, or allowed users |
|
||||
| `remove_channel` | Remove a social channel from a workspace |
|
||||
| `send_channel_message` | Send an outbound message from a workspace to a channel |
|
||||
| `test_channel` | Send a test message to verify a channel connection |
|
||||
| `discover_channel_chats` | Auto-detect chat IDs for a given bot token |
|
||||
|
||||
### Schedules Tools
|
||||
### Schedules Tools (6)
|
||||
| Tool | Description |
|
||||
|------|-------------|
|
||||
| `list_schedules` | List scheduled tasks |
|
||||
| `create_schedule` | Create a new scheduled task |
|
||||
| `delete_schedule` | Delete a scheduled task |
|
||||
| `list_schedules` | List cron schedules for a workspace |
|
||||
| `create_schedule` | Create a cron schedule that fires a prompt on a recurring timer |
|
||||
| `update_schedule` | Update fields on an existing schedule |
|
||||
| `delete_schedule` | Delete a schedule |
|
||||
| `run_schedule` | Fire a schedule manually, bypassing its cron expression |
|
||||
| `get_schedule_history` | Get past runs of a schedule — status, start/end, output |
|
||||
|
||||
### Discovery Tools
|
||||
### Discovery Tools (14)
|
||||
| Tool | Description |
|
||||
|------|-------------|
|
||||
| `check_access` | Verify A2A access between two workspace IDs |
|
||||
| `list_peers` | List reachable peer workspaces (siblings, children, parent) |
|
||||
| `discover_workspace` | Resolve a workspace URL by ID (for A2A communication) |
|
||||
| `check_access` | Check if two workspaces can communicate |
|
||||
| `list_events` | List structure events (global or per workspace) |
|
||||
| `list_templates` | List available workspace templates |
|
||||
| `list_org_templates` | List available org templates |
|
||||
| `import_org` | Import an org template to create an entire workspace hierarchy |
|
||||
| `import_template` | Import agent files as a new workspace template |
|
||||
| `export_bundle` | Export a workspace as a portable .bundle.json |
|
||||
| `import_bundle` | Import a workspace from a bundle JSON object |
|
||||
| `get_canvas_viewport` | Get the current canvas viewport (x, y, zoom) |
|
||||
| `set_canvas_viewport` | Persist the canvas viewport (x, y, zoom) |
|
||||
| `expand_team` | Expand a workspace into a team of sub-workspaces |
|
||||
| `collapse_team` | Collapse a team back to a single workspace |
|
||||
|
||||
### Remote Agents Tools
|
||||
### Remote Agents Tools (4)
|
||||
| Tool | Description |
|
||||
|------|-------------|
|
||||
| `get_remote_agent_info` | Get runtime info for a remote agent |
|
||||
| `heartbeat` | Send a heartbeat to the platform |
|
||||
| `list_remote_agents` | List all workspaces with runtime='external' (Phase 30 remote agents) |
|
||||
| `get_remote_agent_state` | Lightweight state poll for a remote workspace |
|
||||
| `get_remote_agent_setup_command` | Build a bash command to register an agent on a remote machine |
|
||||
| `check_remote_agent_freshness` | Check if a remote agent's heartbeat is recent |
|
||||
|
||||
### Approvals Tools
|
||||
### Approvals Tools (4)
|
||||
| Tool | Description |
|
||||
|------|-------------|
|
||||
| `list_approvals` | List pending approvals for a workspace |
|
||||
| `approve` | Approve a pending item |
|
||||
| `reject` | Reject a pending item |
|
||||
| `list_pending_approvals` | List all pending approval requests across workspaces |
|
||||
| `decide_approval` | Approve or deny a pending approval request |
|
||||
| `create_approval` | Create an approval request for a workspace |
|
||||
| `get_workspace_approvals` | List approval requests for a specific workspace |
|
||||
|
||||
## MCP Transport Gotchas
|
||||
|
||||
|
||||
@@ -2,42 +2,24 @@
|
||||
|
||||
MCP server that exposes Molecule AI platform operations as tools for AI coding agents.
|
||||
|
||||
## 20 Tools Available
|
||||
## 87 Tools Available
|
||||
|
||||
| Tool | Description |
|
||||
|------|-------------|
|
||||
| `list_workspaces` | List all workspaces with status and skills |
|
||||
| `create_workspace` | Create a new workspace (with optional template) |
|
||||
| `get_workspace` | Get workspace details |
|
||||
| `delete_workspace` | Delete workspace (cascades to children) |
|
||||
| `restart_workspace` | Restart offline/failed workspace |
|
||||
| `chat_with_agent` | Send message and get AI response |
|
||||
| `assign_agent` | Assign model to workspace |
|
||||
| `set_secret` | Set API key or env var |
|
||||
| `list_secrets` | List secret keys (no values) |
|
||||
| `list_files` | List workspace config files |
|
||||
| `read_file` | Read a config file |
|
||||
| `write_file` | Create or update a file |
|
||||
| `delete_file` | Delete file or folder |
|
||||
| `commit_memory` | Store fact (LOCAL/TEAM/GLOBAL) |
|
||||
| `search_memory` | Search workspace memories |
|
||||
| `list_templates` | List available templates |
|
||||
| `expand_team` | Expand workspace to team |
|
||||
| `collapse_team` | Collapse team to single workspace |
|
||||
| `list_pending_approvals` | List pending approval requests |
|
||||
| `decide_approval` | Approve or deny a request |
|
||||
See the [full tool registry](CLAUDE.md#mcp-tool-registry) for all tools. Highlights:
|
||||
|
||||
### Phase 30 — Remote agent (SaaS) management
|
||||
|
||||
Tools that surface workspaces with `runtime='external'` (agents that run on
|
||||
machines outside this platform's Docker network and join via HTTP).
|
||||
|
||||
| Tool | Description |
|
||||
|------|-------------|
|
||||
| `list_remote_agents` | Filter the workspace list to remote agents only — id / status / url / heartbeat |
|
||||
| `get_remote_agent_state` | Lightweight `{status, paused, deleted}` projection — faster than `get_workspace` when you only need lifecycle |
|
||||
| `get_remote_agent_setup_command` | Emit a `WORKSPACE_ID=… PLATFORM_URL=… python3 …` bash one-liner an operator can paste into a remote shell |
|
||||
| `check_remote_agent_freshness` | Compare `last_heartbeat_at` against a threshold (default 90s) — returns `{fresh, seconds_since_heartbeat}` |
|
||||
| Category | Tools |
|
||||
|----------|-------|
|
||||
| Workspace | list, create, get, update, delete, restart, pause, resume |
|
||||
| Agent | chat_with, assign, replace, remove, move, get_model |
|
||||
| Delegation | async_delegate, check_delegations, record_delegation, notify_user, list_activity |
|
||||
| Secrets | set, list, delete (workspace + global variants) |
|
||||
| Files | list, read, write, delete, replace_all, get_config, update_config |
|
||||
| Memory | commit, search, delete (HMA scopes) + memory_set/get/list/delete (K/V) |
|
||||
| Plugins | list registry, list installed, install, uninstall, list sources, check compatibility |
|
||||
| Channels | list adapters, list, add, update, remove, send, test, discover chats |
|
||||
| Schedules | list, create, update, delete, run, get history |
|
||||
| Discovery | list peers, discover, check_access, list events, import/export, canvas viewport |
|
||||
| Approvals | list pending, decide, create, get workspace approvals |
|
||||
| Remote Agents | list (runtime=external), get state, setup command, check freshness |
|
||||
|
||||
## Setup
|
||||
|
||||
@@ -52,7 +34,7 @@ Add to your project's `.mcp.json`:
|
||||
"command": "node",
|
||||
"args": ["./mcp-server/dist/index.js"],
|
||||
"env": {
|
||||
"MOLECULE_URL": "http://localhost:8080"
|
||||
"MOLECULE_API_URL": "http://localhost:8080"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -70,7 +52,7 @@ Add to `.cursor/mcp.json`:
|
||||
"command": "node",
|
||||
"args": ["./mcp-server/dist/index.js"],
|
||||
"env": {
|
||||
"MOLECULE_URL": "http://localhost:8080"
|
||||
"MOLECULE_API_URL": "http://localhost:8080"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -80,15 +62,22 @@ Add to `.cursor/mcp.json`:
|
||||
### Codex / OpenCode
|
||||
|
||||
```bash
|
||||
# Run directly
|
||||
MOLECULE_URL=http://localhost:8080 node mcp-server/dist/index.js
|
||||
MOLECULE_API_URL=http://localhost:8080 node mcp-server/dist/index.js
|
||||
```
|
||||
|
||||
## Environment Variables
|
||||
|
||||
| Variable | Default | Description |
|
||||
|----------|---------|-------------|
|
||||
| `MOLECULE_URL` | `http://localhost:8080` | Platform API URL |
|
||||
| `MOLECULE_API_URL` | `http://localhost:8080` | Platform API base URL |
|
||||
| `MOLECULE_API_KEY` | — | API key for platform authentication |
|
||||
| `MCP_SERVER_PORT` | `3000` | Port (for HTTP/SSE transport) |
|
||||
|
||||
## Quick Start
|
||||
|
||||
1. `npm install && npm run build`
|
||||
2. Set `MOLECULE_API_URL` and `MOLECULE_API_KEY`
|
||||
3. `npm start` (stdio mode) or use an MCP host config
|
||||
|
||||
## Examples
|
||||
|
||||
@@ -105,3 +94,15 @@ Agent: [calls chat_with_agent with message="Audit https://example.com for SEO"]
|
||||
You: "What skills does the coding agent have?"
|
||||
Agent: [calls get_workspace, reads agent_card.skills]
|
||||
```
|
||||
|
||||
## Remote Agents (Phase 30)
|
||||
|
||||
For agents running outside the platform's Docker network, the `get_remote_agent_setup_command`
|
||||
tool generates a bash one-liner:
|
||||
|
||||
```bash
|
||||
pip install molecule-ai-sdk
|
||||
WORKSPACE_ID=... PLATFORM_URL=... python3 -c "from molecule_agent import RemoteAgentClient; ..."
|
||||
```
|
||||
|
||||
See the full tool registry in `CLAUDE.md` for all 87 tools.
|
||||
|
||||
+15
-14
@@ -177,23 +177,24 @@ test documenting the known `optional().nullable()` zod-to-json-schema quirk.
|
||||
|
||||
---
|
||||
|
||||
## KI-007 — Heartbeat cleanup fires after SSE stream closes
|
||||
## KI-007 — MCP server heartbeat tools are read-only; actual heartbeat lives in the Python SDK
|
||||
|
||||
**File:** `src/tools/remote_agents.ts` (heartbeat tool)
|
||||
**Status:** Identified
|
||||
**Status:** Resolved — clarified scope
|
||||
**Severity:** Low
|
||||
|
||||
### Symptom
|
||||
When using SSE transport, the heartbeat mechanism does not immediately clean up
|
||||
when a stream closes. A background timer or goroutine may continue sending heartbeats
|
||||
to workspaces whose SSE connections have been closed by the client.
|
||||
### Clarification
|
||||
The MCP server's remote-agent tools (`list_remote_agents`, `get_remote_agent_state`,
|
||||
`check_remote_agent_freshness`, `get_remote_agent_setup_command`) are **read-only
|
||||
queries** — they do not drive any background heartbeat loop. The actual
|
||||
`run_heartbeat_loop()` that sends heartbeats from a remote agent lives in the
|
||||
Python SDK (`molecule_sdk_python/molecule_agent/client.py`).
|
||||
|
||||
### Impact
|
||||
Orphaned heartbeat calls continue consuming platform API quota after the MCP client
|
||||
has disconnected. Over time this can cause the workspace to accumulate heartbeat
|
||||
sessions that never expire on the platform side.
|
||||
The heartbeat cleanup issue (heartbeat loop continues after the controlling MCP
|
||||
client disconnects) is tracked as **SDK KI-009** in `molecule-sdk-python/known-issues.md`.
|
||||
|
||||
### Suggested fix
|
||||
Attach a cleanup function to the SSE stream `close` event. Invalidate the heartbeat
|
||||
timer when the stream ends so no further calls are made. Document the expected
|
||||
SSE session lifecycle in the streaming convention section of CLAUDE.md.
|
||||
### Suggested fix (SDK side)
|
||||
Expose a `stop_event` parameter or `stop()` method on `RemoteAgentClient` so the
|
||||
callers (MCP client, shell wrapper) can signal the loop to exit cleanly. The
|
||||
Python SDK's `run_heartbeat_loop()` should check `threading.Event` or accept a
|
||||
`stop_on: asyncio.Event` argument. See `molecule-sdk-python/known-issues.md`.
|
||||
Generated
+17
-22
@@ -555,10 +555,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@hono/node-server": {
|
||||
"version": "1.19.12",
|
||||
"resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-1.19.12.tgz",
|
||||
"integrity": "sha512-txsUW4SQ1iilgE0l9/e9VQWmELXifEFvmdA1j6WFh/aFPj99hIntrSsq/if0UWyGVkmrRPKA1wCeP+UCr1B9Uw==",
|
||||
"license": "MIT",
|
||||
"version": "1.19.14",
|
||||
"resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-1.19.14.tgz",
|
||||
"integrity": "sha512-GwtvgtXxnWsucXvbQXkRgqksiH2Qed37H9xHZocE5sA3N8O8O8/8FA3uclQXxXVzc9XBZuEOMK7+r02FmSpHtw==",
|
||||
"engines": {
|
||||
"node": ">=18.14.1"
|
||||
},
|
||||
@@ -2555,12 +2554,11 @@
|
||||
}
|
||||
},
|
||||
"node_modules/express-rate-limit": {
|
||||
"version": "8.3.2",
|
||||
"resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-8.3.2.tgz",
|
||||
"integrity": "sha512-77VmFeJkO0/rvimEDuUC5H30oqUC4EyOhyGccfqoLebB0oiEYfM7nwPrsDsBL1gsTpwfzX8SFy2MT3TDyRq+bg==",
|
||||
"license": "MIT",
|
||||
"version": "8.5.1",
|
||||
"resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-8.5.1.tgz",
|
||||
"integrity": "sha512-5O6KYmyJEpuPJV5hNTXKbAHWRqrzyu+OI3vUnSd2kXFubIVpG7ezpgxQy76Zo5GQZtrQBg86hF+CM/NX+cioiQ==",
|
||||
"dependencies": {
|
||||
"ip-address": "10.1.0"
|
||||
"ip-address": "^10.2.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 16"
|
||||
@@ -2596,9 +2594,9 @@
|
||||
"integrity": "sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA=="
|
||||
},
|
||||
"node_modules/fast-uri": {
|
||||
"version": "3.1.0",
|
||||
"resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.0.tgz",
|
||||
"integrity": "sha512-iPeeDKJSWf4IEOasVVrknXpaBV0IApz/gp7S2bb7Z4Lljbl2MGJRqInZiUrQwV16cpzw/D3S5j5Julj/gT52AA==",
|
||||
"version": "3.1.2",
|
||||
"resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.2.tgz",
|
||||
"integrity": "sha512-rVjf7ArG3LTk+FS6Yw81V1DLuZl1bRbNrev6Tmd/9RaroeeRRJhAt7jg/6YFxbvAQXUCavSoZhPPj6oOx+5KjQ==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
@@ -2608,8 +2606,7 @@
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/fastify"
|
||||
}
|
||||
],
|
||||
"license": "BSD-3-Clause"
|
||||
]
|
||||
},
|
||||
"node_modules/fb-watchman": {
|
||||
"version": "2.0.2",
|
||||
@@ -2905,10 +2902,9 @@
|
||||
"integrity": "sha512-7xgomUX6ADmcYzFik0HzAxh/73YlKR9bmFzf51CZwR+b6YtzU2m0u49hQCqV6SvlqIqsaxovfwdvbnsw3b/zpg=="
|
||||
},
|
||||
"node_modules/hono": {
|
||||
"version": "4.12.10",
|
||||
"resolved": "https://registry.npmjs.org/hono/-/hono-4.12.10.tgz",
|
||||
"integrity": "sha512-mx/p18PLy5og9ufies2GOSUqep98Td9q4i/EF6X7yJgAiIopxqdfIO3jbqsi3jRgTgw88jMDEzVKi+V2EF+27w==",
|
||||
"license": "MIT",
|
||||
"version": "4.12.18",
|
||||
"resolved": "https://registry.npmjs.org/hono/-/hono-4.12.18.tgz",
|
||||
"integrity": "sha512-RWzP96k/yv0PQfyXnWjs6zot20TqfpfsNXhOnev8d1InAxubW93L11/oNUc3tQqn2G0bSdAOBpX+2uDFHV7kdQ==",
|
||||
"engines": {
|
||||
"node": ">=16.9.0"
|
||||
}
|
||||
@@ -3015,10 +3011,9 @@
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/ip-address": {
|
||||
"version": "10.1.0",
|
||||
"resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.1.0.tgz",
|
||||
"integrity": "sha512-XXADHxXmvT9+CRxhXg56LJovE+bmWnEWB78LB83VZTprKTmaC5QfruXocxzTZ2Kl0DNwKuBdlIhjL8LeY8Sf8Q==",
|
||||
"license": "MIT",
|
||||
"version": "10.2.0",
|
||||
"resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.2.0.tgz",
|
||||
"integrity": "sha512-/+S6j4E9AHvW9SWMSEY9Xfy66O5PWvVEJ08O0y5JGyEKQpojb0K0GKpz/v5HJ/G0vi3D2sjGK78119oXZeE0qA==",
|
||||
"engines": {
|
||||
"node": ">= 12"
|
||||
}
|
||||
|
||||
+1
-1
@@ -29,6 +29,6 @@
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/Molecule-AI/molecule-mcp-server.git"
|
||||
"url": "https://git.moleculesai.app/molecule-ai/molecule-mcp-server.git"
|
||||
}
|
||||
}
|
||||
|
||||
+26
-2
@@ -1,3 +1,5 @@
|
||||
import { error as logError } from "./utils/logger.js";
|
||||
|
||||
// Read the platform API base URL from environment.
|
||||
// Priority: MOLECULE_API_URL (canonical CLI/SDK env var, per platform docs)
|
||||
//
|
||||
@@ -19,8 +21,6 @@ export const PLATFORM_URL =
|
||||
* Shape returned by apiCall when the request fails (network error, non-2xx,
|
||||
* or non-JSON body with no error). Returned-by-value — apiCall never throws.
|
||||
*/
|
||||
import { error as logError } from "./utils/logger.js";
|
||||
|
||||
export type ApiError = { error: string; detail?: string; raw?: string; status?: number };
|
||||
|
||||
export function isApiError(v: unknown): v is ApiError {
|
||||
@@ -45,16 +45,24 @@ 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();
|
||||
@@ -68,7 +76,12 @@ 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 };
|
||||
}
|
||||
}
|
||||
@@ -88,7 +101,9 @@ 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) {
|
||||
@@ -96,6 +111,7 @@ 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) {
|
||||
@@ -137,7 +153,15 @@ 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,6 +48,8 @@ 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 }> } }
|
||||
>(
|
||||
@@ -59,6 +61,7 @@ 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,7 +8,9 @@ export async function handleAsyncDelegate(params: {
|
||||
task: string;
|
||||
}) {
|
||||
const { workspace_id, target_id, task } = params;
|
||||
const data = await apiCall("POST", `/workspaces/${workspace_id}/delegate`, { target_id, task });
|
||||
// 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);
|
||||
return toMcpResult(data);
|
||||
}
|
||||
|
||||
|
||||
@@ -85,7 +85,7 @@ export async function handleGetRemoteAgentSetupCommand(params: {
|
||||
const setupCmd = [
|
||||
`# Run on the remote machine where the agent will live.`,
|
||||
`# Requires Python 3.11+ and bash (the SDK invokes setup.sh via bash).`,
|
||||
`pip install molecule-sdk # (or: pip install -e <molecule-checkout>/sdk/python)`,
|
||||
`pip install molecule-ai-sdk # (or: pip install -e <molecule-checkout>/molecule-sdk-python)`,
|
||||
``,
|
||||
`WORKSPACE_ID=${w.id} \\`,
|
||||
`PLATFORM_URL=${targetUrl} \\`,
|
||||
@@ -95,7 +95,7 @@ export async function handleGetRemoteAgentSetupCommand(params: {
|
||||
` c.run_heartbeat_loop()"`,
|
||||
``,
|
||||
`# For a richer demo (logging, graceful shutdown) see`,
|
||||
`# sdk/python/examples/remote-agent/run.py in the molecule-monorepo checkout.`,
|
||||
`# examples/remote-agent/run.py in the molecule-sdk-python checkout.`,
|
||||
`# The agent will register, mint its bearer token (cached at`,
|
||||
`# ~/.molecule/${w.id}/.auth_token), pull secrets, then heartbeat.`,
|
||||
].join("\n");
|
||||
|
||||
@@ -150,6 +150,25 @@ 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 });
|
||||
|
||||
@@ -183,6 +202,17 @@ 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);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -222,6 +252,20 @@ 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