Skip to content

Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.

library: an MCP server's startup timeout reaches Codex as startup_timeout_sec, a hand-written one stays (#3168, miaomiaozi)

yetone769355ab938a
diff --git a/docs/subsystems/library.md b/docs/subsystems/library.md
index fb818641a..d436b672a 100644
--- a/docs/subsystems/library.md
+++ b/docs/subsystems/library.md
@@ -19,7 +19,7 @@ agents RTK, a CLI that cuts shell output down before the model reads it.
| Sync | `sync` writes each target's instructions and MCP servers. It then takes edits made in agents' skill copies into the library (`takeEdits`) and links or copies the skills. `~/.agents/skills` goes first, so an agent that reads it gets no second link. Then it syncs projects' skills. | [`sync.go`](../../internal/library/sync.go) |
| Projects | A project (`Project`) is a folder given some of the library's skills and MCP servers, each for some agents. A skill is linked (or copied) into the folder the agent reads a project's skills from (`projectSkillsDirs`): `.claude/skills` for Claude Code, `.qoder/skills` for Qoder and Qoder CN, `.codebuddy/skills` for CodeBuddy Code, `.commandcode/skills` for Command Code, and `.agents/skills` for Codex, Gemini CLI, OpenCode, Pi, Cursor, Copilot CLI, Antigravity, Kimi, Goose, Grok, Droid and Cline. A server is written into the file the agent reads a project's servers from (`projectMCPFiles`), in the shape its user-wide file has: `.mcp.json` for Claude Code and CodeBuddy Code (CodeBuddy's `mcp.json` when the project has that and no `.mcp.json`, since it reads only the first of the two), `.codex/config.toml`, `.gemini/settings.json`, `.cursor/mcp.json`, `opencode.json`, `.zcode/config.json`, `.pi/mcp.json`, `.qoder/settings.json`'s `mcpServers` for Qoder and Qoder CN, and `.factory/mcp.json` for Droid. Claude Code, Qoder and CodeBuddy ask the user to approve a project's server before using it. Only targets whose vendor source or docs name them are listed (each map's comment cites them); an agent with none (Copilot CLI's MCP, Zed, WorkBuddy, Command Code's MCP, whose `.mcp.json` has its own `transport` shape) can't be picked for a project (eirc on Discord). `Placed`, `Wrote`, `Made` and `MadeFiles` record what magpie put there, the only things it takes away, and what it made is listed in the project's `.gitignore`. | [`projects.go`](../../internal/library/projects.go), [`project_mcp.go`](../../internal/library/project_mcp.go) |
| Instructions | magpie's part of an agent's instructions file sits between two marker lines. The rest of the file is the user's. Several named sets can be switched between (#106). A set can be kept in a file of the user's own instead of `instruction-sets/` (`InstrSet.File`, 新v学员 on Discord): `~/.agents/AGENTS.md`, which Droid and omp read too. `textPath` reads it, `putText` keeps it aside and writes it but never removes it, removing the set lets go of it, and `linkable` refuses a file magpie writes into (an agent's own instructions, a file with the marker line), the library's own and another set's. The app's `KeepLinked` looks at the file every 30 s and writes a change into the agents (`SyncLinked`). A set's text is read without magpie's part (`setText`), and an agent whose instructions file is, links followed, the file the set on is kept in (`isSetFile`: `instructions.md` linked to `~/.claude/CLAUDE.md`, or both linked to one dotfile) gets no part written into it, and one written before is taken out with every part nested in it: read with its part, each sync wrote the whole file into that part again and it doubled, to gigabytes (#2349, `TestInstructionsSetLinkedToAgentsFile`). `Collect` carries the set's text, not where its file is; `Put` keeps this computer's file for the set and never empties it for a text not carried. Alma's file is `~/.config/alma/USER.md`, which its main chat reads into its system prompt as its owner's profile (0.4.164's `out/main/index.js`; a workspace's `USER.md` is read instead), and whose leading front matter (`name`, `telegram_id`, `discord_id`) is who its bots answer to (#2315, Jie211). The target is a `Profile`: magpie's part goes after the user's, so the front matter stays first, and `ImportInstructions` refuses it, as moving it out would take that front matter out of the file and into every agent's (`TestAlmaInstructionsKeepTheProfile`, `TestAlmaProfileIsNotImported`, `library-alma-profile.test.cjs`). | [`instructions.go`](../../internal/library/instructions.go) |
-| MCP servers | A `Server` is a command or a URL (`http`, `sse`). `mcpFile` encodes it in each agent's own format (one `mcpFormat` per agent family) and merges it with the user's own fields for that entry. `Also` files get the same servers; `Extra` files are only read when importing. `CheckServers` connects as an agent would and keeps the result in memory only: with each tool's name and the first paragraph of its description (`ToolList`, at most `maxToolList`, a description cut at `maxToolDesc` runes), which the page lists when the server's "N tools" is clicked, following tools/list's `nextCursor` up to `maxToolPages` pages (`listTools`). Each step (initialize, notifications/initialized, tools/list; connect for SSE) has its own budget, 60s for a URL and 30s for a command (`remoteStep`, `stdioStep`), and a timeout names its `Step` and how long it `Waited`; a timeout isn't kept, so the next look asks again (#1467). The page asks once a session for the servers some agent or project has (`inUse` in plugins/library/client.js); one no agent has shows "not checked" and is checked only when its status is clicked (#1597, `library-mcp-health.test.cjs`). A server checked once is checked again when it changes, its sign-in included, so a server signed in to after a click's "needs sign-in" isn't left showing both (新v学员 on Discord, `mcp-signin-health.test.cjs`). The check sends magpie's sign-in as the gateway does: on a 401 it renews the token once and asks again, and a server that refuses even the renewed token has the sign-in marked run out (`mcpauth.Rejected`, also from the gateway's `/mcp/<name>`), which `ServerHealth.SignIn` carries back so the row's tag says "Sign-in ran out" rather than "Signed in" beside "needs sign-in". A server that refuses the check (401 or 403) but that an agent signed in to on its own is named so (`ServerHealth.AgentSignIn`, `readOwnSignIns` in `mcp_agent_signin.go`): each Claude Code target's `.credentials.json` beside its settings.json, a WSL distro's under the distro's home, is read for a `mcpOAuth` entry of the server's name and URL with a token, and the row says "signed in in Claude Code (Ubuntu)" instead of "needs sign-in" (CyberCaius on Discord: signed in to with Claude Code's /mcp in WSL). The tokens are never sent or kept; a file that can't be read or parsed names nobody, a stopped distro isn't started for it, and on a Mac only the file is read, never the Keychain Claude Code keeps them in. They are part of the check's key, so a sign-in in the agent since is checked anew (`TestCheckNamesAgentsSignedInThemselves`, `library-mcp-health-wsl.test.cjs`). A server that needs OAuth is signed in once in magpie, and agents reach it through the gateway's `/mcp/<name>` (#615). The editor's Sign in saves the form first only when the sign-in is to another server than the saved one (a new server, a name or URL changed), and its button then reads "Save and sign in"; anything else edited (headers, env, arguments) stays unsaved until Save, so Cancel leaves the server as it was (新v学员 on Discord, `mcp-editor-cancel.test.cjs`). A server whose authorization server refuses magpie's dynamic client registration with 401 or 403 admits only the clients it lists (Figma's, #1619): the sign-in fails with `mcpauth.ErrClientRefused`, which says so and that each agent signs in itself, and the agents keep the server's own address. A server whose authorization server has no registration endpoint at all (GitHub's remote server, 新v学员 on Discord) fails with `mcpauth.ErrNoRegistration`, which says to make an OAuth app with the vendor and give it in the editor; the editor then opens its "OAuth app" fields. The app is the server's `oauth` (`OAuthApp`: `clientId`, `clientSecret`, `callbackPort`, Claude Code's names for `--client-id`, `--client-secret` and `--callback-port`), checked on save (HTTP only, a client ID, a port from 1 to 65535), and `SignInServer` signs in as it through `mcpauth.StartWith` without registering. The callback is Claude Code's, `http://localhost:<port>/callback` (its docs' "Use pre-configured OAuth credentials"; 2.1.296 builds it so), listened for on 127.0.0.1 alone as Claude Code does, so an app made for Claude Code signs magpie in as it is; a server that matches the registered URL exactly refuses another host, which is why Claude Code's 2.1.231 went back to `localhost` from 2.1.229's `127.0.0.1` (`TestAppMadeForClaudeCode`). Without a `callbackPort` the port is any free one, which a loopback callback registered without a port takes (GitHub's, RFC 8252); a fixed `callbackPort` is for a vendor that matches the port too. magpie's own registration, when a server has one, still names `127.0.0.1`. The client secret is kept in library.json, as a header's or env's value is: a backup without keys leaves it out, and `WithSecrets` puts back this computer's secret only for the same client ID; no agent is given the app, and the TUI's editor, which doesn't show it, keeps it. GitHub answers a token request's error with a 200 and `error` in the body (`bad_refresh_token`, `incorrect_client_credentials`), which `tokenRequest` reads as the error it is, and a dead refresh token marks the sign-in run out (`github_app_test.go`, `mcp-oauth-app.test.cjs`). magpie never registers under another client's name; one that reaches the gateway from another machine (a WSL distro under NAT) is given it with the LAN sharing key as its `Authorization` (`agent.KeyAt`), as its models are, which the gateway takes in place of a sign-in and never passes on; turning sharing on or off, or a new key (`access.LANChanged`), writes such entries again. `ConfigOfServers` is the servers picked as an agent's project file (`projectMCPFiles`) would hold them, written by the same code into a folder of its own and read back, with those the agent can't take there named; the page's Copy config… puts it on the clipboard for a project magpie doesn't keep (#1478). Each listed tool has a switch: the tools turned off are the server's `DisabledTools`, set by `ServerTools`, and written into each agent given the server that can leave out a single tool (see the constraint below). | [`mcp.go`](../../internal/library/mcp.go), [`mcp_check.go`](../../internal/library/mcp_check.go), [`mcp_signin.go`](../../internal/library/mcp_signin.go), [`mcp_agent_signin.go`](../../internal/library/mcp_agent_signin.go), [`mcp_copy.go`](../../internal/library/mcp_copy.go), [`mcp_tools_off.go`](../../internal/library/mcp_tools_off.go) |
+| MCP servers | A `Server` is a command or a URL (`http`, `sse`). `mcpFile` encodes it in each agent's own format (one `mcpFormat` per agent family) and merges it with the user's own fields for that entry. A server's `StartupTimeout` (#3168) goes to Codex alone, as `startup_timeout_sec` in seconds (`RawMcpServerConfig` in codex-rs/config's mcp_types.rs; 0 leaves Codex's own 30s), in the user-wide config.toml and a project's alike. magpie keeps the value it wrote (`Applied.Startup`, `Project.Startup`): one in the entry other than that, or a `startup_timeout_ms`, is the user's and stays as it is (`startupTheirs`), and once it is taken out magpie's goes in again. The editor shows the field only when an agent that takes it is here (`AgentView.Startup`, `mcp_startup_test.go`, `mcp-startup-timeout.test.cjs`). `Also` files get the same servers; `Extra` files are only read when importing. `CheckServers` connects as an agent would and keeps the result in memory only: with each tool's name and the first paragraph of its description (`ToolList`, at most `maxToolList`, a description cut at `maxToolDesc` runes), which the page lists when the server's "N tools" is clicked, following tools/list's `nextCursor` up to `maxToolPages` pages (`listTools`). Each step (initialize, notifications/initialized, tools/list; connect for SSE) has its own budget, 60s for a URL and 30s for a command (`remoteStep`, `stdioStep`), and a timeout names its `Step` and how long it `Waited`; a timeout isn't kept, so the next look asks again (#1467). The page asks once a session for the servers some agent or project has (`inUse` in plugins/library/client.js); one no agent has shows "not checked" and is checked only when its status is clicked (#1597, `library-mcp-health.test.cjs`). A server checked once is checked again when it changes, its sign-in included, so a server signed in to after a click's "needs sign-in" isn't left showing both (新v学员 on Discord, `mcp-signin-health.test.cjs`). The check sends magpie's sign-in as the gateway does: on a 401 it renews the token once and asks again, and a server that refuses even the renewed token has the sign-in marked run out (`mcpauth.Rejected`, also from the gateway's `/mcp/<name>`), which `ServerHealth.SignIn` carries back so the row's tag says "Sign-in ran out" rather than "Signed in" beside "needs sign-in". A server that refuses the check (401 or 403) but that an agent signed in to on its own is named so (`ServerHealth.AgentSignIn`, `readOwnSignIns` in `mcp_agent_signin.go`): each Claude Code target's `.credentials.json` beside its settings.json, a WSL distro's under the distro's home, is read for a `mcpOAuth` entry of the server's name and URL with a token, and the row says "signed in in Claude Code (Ubuntu)" instead of "needs sign-in" (CyberCaius on Discord: signed in to with Claude Code's /mcp in WSL). The tokens are never sent or kept; a file that can't be read or parsed names nobody, a stopped distro isn't started for it, and on a Mac only the file is read, never the Keychain Claude Code keeps them in. They are part of the check's key, so a sign-in in the agent since is checked anew (`TestCheckNamesAgentsSignedInThemselves`, `library-mcp-health-wsl.test.cjs`). A server that needs OAuth is signed in once in magpie, and agents reach it through the gateway's `/mcp/<name>` (#615). The editor's Sign in saves the form first only when the sign-in is to another server than the saved one (a new server, a name or URL changed), and its button then reads "Save and sign in"; anything else edited (headers, env, arguments) stays unsaved until Save, so Cancel leaves the server as it was (新v学员 on Discord, `mcp-editor-cancel.test.cjs`). A server whose authorization server refuses magpie's dynamic client registration with 401 or 403 admits only the clients it lists (Figma's, #1619): the sign-in fails with `mcpauth.ErrClientRefused`, which says so and that each agent signs in itself, and the agents keep the server's own address. A server whose authorization server has no registration endpoint at all (GitHub's remote server, 新v学员 on Discord) fails with `mcpauth.ErrNoRegistration`, which says to make an OAuth app with the vendor and give it in the editor; the editor then opens its "OAuth app" fields. The app is the server's `oauth` (`OAuthApp`: `clientId`, `clientSecret`, `callbackPort`, Claude Code's names for `--client-id`, `--client-secret` and `--callback-port`), checked on save (HTTP only, a client ID, a port from 1 to 65535), and `SignInServer` signs in as it through `mcpauth.StartWith` without registering. The callback is Claude Code's, `http://localhost:<port>/callback` (its docs' "Use pre-configured OAuth credentials"; 2.1.296 builds it so), listened for on 127.0.0.1 alone as Claude Code does, so an app made for Claude Code signs magpie in as it is; a server that matches the registered URL exactly refuses another host, which is why Claude Code's 2.1.231 went back to `localhost` from 2.1.229's `127.0.0.1` (`TestAppMadeForClaudeCode`). Without a `callbackPort` the port is any free one, which a loopback callback registered without a port takes (GitHub's, RFC 8252); a fixed `callbackPort` is for a vendor that matches the port too. magpie's own registration, when a server has one, still names `127.0.0.1`. The client secret is kept in library.json, as a header's or env's value is: a backup without keys leaves it out, and `WithSecrets` puts back this computer's secret only for the same client ID; no agent is given the app, and the TUI's editor, which doesn't show it, keeps it. GitHub answers a token request's error with a 200 and `error` in the body (`bad_refresh_token`, `incorrect_client_credentials`), which `tokenRequest` reads as the error it is, and a dead refresh token marks the sign-in run out (`github_app_test.go`, `mcp-oauth-app.test.cjs`). magpie never registers under another client's name; one that reaches the gateway from another machine (a WSL distro under NAT) is given it with the LAN sharing key as its `Authorization` (`agent.KeyAt`), as its models are, which the gateway takes in place of a sign-in and never passes on; turning sharing on or off, or a new key (`access.LANChanged`), writes such entries again. `ConfigOfServers` is the servers picked as an agent's project file (`projectMCPFiles`) would hold them, written by the same code into a folder of its own and read back, with those the agent can't take there named; the page's Copy config… puts it on the clipboard for a project magpie doesn't keep (#1478). Each listed tool has a switch: the tools turned off are the server's `DisabledTools`, set by `ServerTools`, and written into each agent given the server that can leave out a single tool (see the constraint below). | [`mcp.go`](../../internal/library/mcp.go), [`mcp_check.go`](../../internal/library/mcp_check.go), [`mcp_signin.go`](../../internal/library/mcp_signin.go), [`mcp_agent_signin.go`](../../internal/library/mcp_agent_signin.go), [`mcp_copy.go`](../../internal/library/mcp_copy.go), [`mcp_tools_off.go`](../../internal/library/mcp_tools_off.go) |
| Skills | A skill is a folder with a `SKILL.md`. It comes from GitHub, from any other git repository, from a folder on this machine (linked, so editing the folder edits the skill) or from the market. A git repository (`kind: git`, sunset on Discord: GitLab, a company's own GitLab) is any https, http, ssh or `file://` address, `git@host:group/repo.git`, a bare `host.name/group/repo`, or a GitLab or Gitea page of a folder (`/-/tree/<ref>/<path>`, `/-/blob/…`, `/src/branch/…`; a branch with a `/` in its name is read as its first segment) (`gitSource`). It is fetched by the user's own `git` (`proc.FindTool`), so their credential helpers and SSH keys reach an intranet host: `git init`, then `fetch --depth 1 --no-tags -- <url> <ref>` and `checkout FETCH_HEAD` into a `magpie-skill-*` folder, then its `.git` is removed (`fetchGit`). What the user typed is data: an address starting with `-` and a `transport::` address (`ext::`, `fd::`, `file::`) are refused before git runs, the address follows `--`, git runs with `protocol.ext.allow=never` and `core.symlinks=false`, no shell, `GIT_TERMINAL_PROMPT=0` and (unless the user set an SSH command) `ssh -o BatchMode=yes`, so a sign-in it can't make fails instead of waiting. An address with a password or token in it is refused: library.json is shown and backed up. Git missing, a sign-in refused, a host key unknown, a branch missing and a host unreachable each say so (`gitError`; `TestGitSourceReads`, `TestInstallFromGitRepo`, `TestGitTreeURLInstallsFolder`, `TestGitMissingSaysSo`, `TestGitSignInRefusedSaysSo`, `TestGitRefusesOptionsAndTransports`, `TestGitErrorsSaid`). Each agent gets a link or a marked copy (#896, `SkillHow`). An agent in a WSL distro always gets a copy. A copy's mark keeps the hash of what was copied, so a sync knows a copy unchanged since then is current without reading its files (`copyIsFresh`, #1031); other copies are hashed. A skill an agent has of its own (`foundSkills`, the page's "In your agents") is brought in with `ImportSkill`, or taken out of every agent that has it with `RemoveFoundSkill` (#1303): its folders and copies of the very same files, its shared `~/.agents/skills` entry and a folder of it in the library's own folder go to the backups, its links are taken away, and a folder elsewhere it only links to, or another skill by that name, stays. Several go at once with `RemoveFoundSkills` (`POST /api/library/skills/remove-found-some`, wongxy on Discord): the "In your agents" heading's own Select picks them, and Remove… asks once, naming the count, before one change takes each out as `RemoveFoundSkill` would. A name that can't be taken out is left as it was, in `Result.Unremoved`, and stays picked with its error in its row's place (`foundErrs`); when none can go the change fails and nothing is touched. This Select and the library's are never on together: while one is on the other is dimmed, saying why, so neither click takes the other's bar away from above the pointer (`TestRemoveFoundSkills`, `found-skill-pick-remove.test.cjs`). A repository is fetched as one tarball of at most `maxFetch` (200 MB); a bigger one is fetched file by file from its tree (`fetchSkillFiles`), and a skill over 200 MB on its own is left out rather than failing the rest: the probe lists the others and names it in `Probe.Left`, under the list in the page and in the TUI's flash. Only when every skill is too big does the fetch fail (#2062, mikubaka88/CCFA-Skills' 297 MB ccf-paper-writer; `TestOneSkillTooBigLeavesTheOthers`, `skill-too-big.test.cjs`). A probe keeps its download for the install from it for 15 minutes (`keepProbe`, `probeLife`), and removes it when it is probed again or that time is up, not at the next probe, which may never come. A download a magpie that quit left in the temp dir goes at the next probe once it is an hour old (`sweepStaleDownloads`). The package's TestMain gives the tests a temp dir of their own and fails a run that leaves a `magpie-skill-*` in it (#2321, `TestProbeDownloadEndsWithIt`, `TestStaleDownloadsSwept`). | [`skilltree.go`](../../internal/library/skilltree.go), [`skills.go`](../../internal/library/skills.go), [`skillgit.go`](../../internal/library/skillgit.go), [`skill_how.go`](../../internal/library/skill_how.go), [`skill_edits.go`](../../internal/library/skill_edits.go), [`skill_from.go`](../../internal/library/skill_from.go) |
| Skills market | `MarketSkills` lists skills.sh's most installed and what its search finds. magpie's own skills (`featuredSkills`) go first, marked official: `magpie-quota`, in [magpie-community/plugins](https://github.com/magpie-community/plugins/tree/main/skills/magpie-quota), lets an agent read `magpie quota --json` and wait with `magpie quota wait`. Until skills.sh lists one it has no count of installs and no skills.sh link (`featured`). `InstallMarketSkill` installs any of them from its repository. | [`market.go`](../../internal/library/market.go) |
| Skills a repository added | A check for updates (`CheckSkills`) also asks, for each GitHub repository and ref the library has skills from, GitHub's list of its files (`repoTree`, one API request, free when the ETag still matches). Only when that list has a skill folder beside the installed ones (under `newBase`, their deepest common folder) that the library doesn't have and hasn't offered does `findNew` fetch the repository for the skills' names and descriptions. `SeenSkills` records per `repo@ref` the paths the install picker showed and the ones set aside, so they aren't offered again. The finds live in memory (`newFound`) and reach the page as `View.NewSkills`; `AddNewSkills` gives each to the agents that have its repository's other skills, and `IgnoreNewSkills` sets it aside (`/api/library/skills/{add-new,ignore-new}`). | [`skillnew.go`](../../internal/library/skillnew.go), [`skillcheck.go`](../../internal/library/skillcheck.go) |
diff --git a/internal/gui/assets/plugins/library/client.js b/internal/gui/assets/plugins/library/client.js
index a0fd4bc22..9354a84b2 100644
--- a/internal/gui/assets/plugins/library/client.js
+++ b/internal/gui/assets/plugins/library/client.js
@@ -2160,6 +2160,19 @@ magpie.plugin("library", (ctx) => {
g.append(...field(t("Sign-in"), signBox, t("For a server that asks you to sign in (OAuth): magpie signs in once, and every agent given it uses that sign-in")));
} else appBox = null;
}
+ // how long the agents that take one (Codex's startup_timeout_sec)
+ // wait for it to start, shown only when one of them is here (#3168)
+ const slow = [...new Set(all.filter((a) => a.startup).map((a) => a.name))];
+ if (slow.length) {
+ const wait = field2(d.startupTimeout || "", "30", (v) => {
+ wait.value = v.replace(/\D/g, "").slice(0, 5);
+ d.startupTimeout = Number(wait.value) || 0;
+ });
+ wait.inputMode = "numeric";
+ wait.classList.add("lib-startup");
+ wait.setAttribute("aria-label", t("Startup timeout"));
+ g.append(...field(t("Startup timeout"), wait, t("Seconds {agents} waits for it to start and list its tools. Empty leaves {agents}'s own 30; a value you wrote in its config.toml by hand is kept", { agents: slow.join(", ") })));
+ }
slot.append(g);
if (appBox) drawApp();
// its own icon while it runs as it did; another way of running is another server
@@ -2178,7 +2191,7 @@ magpie.plugin("library", (ctx) => {
// send saves the form; s is then the server as saved, for a save after
// a sign-in's to be of it
const send = async () => {
- const body = { old: s ? s.name : "", server: { name: d.name, transport: d.transport, agents: d.agents } };
+ const body = { old: s ? s.name : "", server: { name: d.name, transport: d.transport, agents: d.agents, startupTimeout: d.startupTimeout || 0 } };
if (d.transport === "stdio") Object.assign(body.server, { command: d.command, args: d.args, env: d.env });
else Object.assign(body.server, { url: d.url, headers: d.headers, oauth: d.transport === "http" && d.oauth?.clientId ? d.oauth : null });
take(await api("library/servers/save", body));
diff --git a/internal/gui/assets/plugins/library/i18n.js b/internal/gui/assets/plugins/library/i18n.js
index 42aa949cc..9c655a38a 100644
--- a/internal/gui/assets/plugins/library/i18n.js
+++ b/internal/gui/assets/plugins/library/i18n.js
@@ -85,6 +85,8 @@ magpie.strings({
"Client ID": "客户端 ID",
"Client secret": "客户端密钥",
"Callback port": "回调端口",
+ "Startup timeout": "启动超时",
+ "Seconds {agents} waits for it to start and list its tools. Empty leaves {agents}'s own 30; a value you wrote in its config.toml by hand is kept": "{agents} 等它启动并列出工具的秒数。留空用 {agents} 自己的 30 秒;你在它的 config.toml 里手写的值会保留",
"Made with its vendor (GitHub's under Settings › Developer settings › OAuth Apps), with {url} as its callback URL": "在服务方创建(GitHub 的在 Settings › Developer settings › OAuth Apps),回调 URL 填 {url}",
"Open it to sign in again": "打开它重新登录",
"Signed in to {name} — the agents given it use magpie's sign-in": "已登录 {name},分配到它的 agent 共用 magpie 的登录",
@@ -715,6 +717,8 @@ magpie.strings({
"Client ID": "用戶端 ID",
"Client secret": "用戶端密鑰",
"Callback port": "回呼連接埠",
+ "Startup timeout": "啟動逾時",
+ "Seconds {agents} waits for it to start and list its tools. Empty leaves {agents}'s own 30; a value you wrote in its config.toml by hand is kept": "{agents} 等它啟動並列出工具的秒數。留空用 {agents} 自己的 30 秒;你在它的 config.toml 裡手寫的值會保留",
"Made with its vendor (GitHub's under Settings › Developer settings › OAuth Apps), with {url} as its callback URL": "在服務方建立(GitHub 的在 Settings › Developer settings › OAuth Apps),回呼 URL 填 {url}",
"Open it to sign in again": "開啟它重新登入",
"Signed in to {name} — the agents given it use magpie's sign-in": "已登入 {name},分配到它的 agent 共用 magpie 的登入",
@@ -1340,6 +1344,8 @@ magpie.strings({
"Client ID": "クライアント ID",
"Client secret": "クライアントシークレット",
"Callback port": "コールバックポート",
+ "Startup timeout": "起動タイムアウト",
+ "Seconds {agents} waits for it to start and list its tools. Empty leaves {agents}'s own 30; a value you wrote in its config.toml by hand is kept": "{agents} が起動してツールを一覧するまで待つ秒数。空欄なら {agents} 自身の 30 秒。config.toml に手で書いた値はそのまま残ります",
"Made with its vendor (GitHub's under Settings › Developer settings › OAuth Apps), with {url} as its callback URL": "提供元で作成し(GitHub は Settings › Developer settings › OAuth Apps)、コールバック URL に {url} を指定します",
"Open it to sign in again": "開いて再度サインイン",
"Signed in to {name} — the agents given it use magpie's sign-in": "{name} にサインインしました。割り当てられたエージェントは magpie のサインインを使います",
@@ -1968,6 +1974,8 @@ magpie.strings({
"Client ID": "Client-ID",
"Client secret": "Client-Secret",
"Callback port": "Callback-Port",
+ "Startup timeout": "Start-Timeout",
+ "Seconds {agents} waits for it to start and list its tools. Empty leaves {agents}'s own 30; a value you wrote in its config.toml by hand is kept": "Sekunden, die {agents} wartet, bis er startet und seine Tools auflistet. Leer lässt die eigenen 30 von {agents}; ein Wert, den du in seiner config.toml von Hand gesetzt hast, bleibt erhalten",
"Made with its vendor (GitHub's under Settings › Developer settings › OAuth Apps), with {url} as its callback URL": "Beim Anbieter angelegt (bei GitHub unter Settings › Developer settings › OAuth Apps), mit {url} als Callback-URL",
"Open it to sign in again": "Öffnen, um sich erneut anzumelden",
"Signed in to {name} — the agents given it use magpie's sign-in": "Bei {name} angemeldet — die zugewiesenen Agenten nutzen die Anmeldung von magpie",
diff --git a/internal/gui/assets/plugins/library/library.css b/internal/gui/assets/plugins/library/library.css
index 41f3793ea..f6fd15dac 100644
--- a/internal/gui/assets/plugins/library/library.css
+++ b/internal/gui/assets/plugins/library/library.css
@@ -139,6 +139,7 @@ body.window .lib-head { top: -2px; margin: -2px 0 0; padding: 8px 0 4px; --bleed
.lib-app { display: flex; gap: 6px; width: 100%; align-items: center; flex-wrap: wrap; }
.lib-app input { flex: 1 1 9em; min-width: 0; font-family: var(--code-font, var(--code)); font-size: 12px; }
.lib-app input.port { flex: 0 1 7.5em; }
+.lib-editor input.lib-startup { max-width: 140px; }
.lib-signin-err { margin-top: 6px; font-size: 12px; color: var(--red); line-height: 1.45; overflow-wrap: anywhere; }
.lib-signin-link { display: flex; align-items: center; gap: 4px; margin-top: 5px; min-width: 0; }
.lib-signin-link code { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font: var(--code-style, normal) var(--code-weight, 400) 11px/1.3 var(--code-font, var(--code)); font-stretch: var(--code-stretch, 100%); color: var(--fg-2); padding: 4px 7px; border: 1px solid var(--line); border-radius: 6px; background: var(--card); user-select: all; -webkit-user-select: all; cursor: text; }
diff --git a/internal/gui/tests/mcp-startup-timeout.test.cjs b/internal/gui/tests/mcp-startup-timeout.test.cjs
new file mode 100644
index 000000000..4ae0610ed
--- /dev/null
+++ b/internal/gui/tests/mcp-startup-timeout.test.cjs
@@ -0,0 +1,118 @@
+// Run with Node's test runner and Playwright on the module path; see README.md.
+// #3168 (miaomiaozi on Discord): a slow-starting MCP server couldn't be
+// given a longer startup timeout in magpie. The server's editor has a
+// "Startup timeout" in seconds, shown only when an agent that takes one
+// (Codex, startup_timeout_sec) is here, digits only, saved with the
+// server as startupTimeout and shown again; emptied, it saves 0 (the
+// agent's own). Every language, Chromium and WebKit, 1100 and 390 wide;
+// nothing scrolls sideways. No backend: the API is faked here.
+const assert = require("node:assert/strict");
+const fs = require("node:fs/promises");
+const path = require("node:path");
+const { test } = require("node:test");
+const { chromium, webkit } = require("playwright");
+
+const assets = path.resolve(__dirname, "../assets");
+const { I18N } = require("./strings.cjs").strings(); // i18n.js's and the plugins'
+const tr = (lang, s, vars = {}) => ((lang === "en" ? s : I18N[lang][s]) || s).replace(/\{(\w+)\}/g, (_, k) => vars[k]);
+const HOME = "/Users/xv";
+const agent = (id, name) => ({ id, name, icon: "", skills: `${HOME}/.${id}/skills`, mcp: `${HOME}/.${id}/mcp.json` });
+
+
+function server(lang, calls, agents) {
+ const lib = {
+ dir: `${HOME}/.magpie/library`, backups: `${HOME}/.magpie/backups`, home: HOME,
+ agents,
+ instructions: { agents: [], sets: [] }, foundServers: [], projects: [], foundSkills: [], skills: [],
+ servers: [{ name: "slow", transport: "stdio", command: "npx", args: ["-y", "slow-mcp"], agents: agents.map((a) => a.id) }],
+ };
+ return async (route) => {
+ const req = route.request(), url = new URL(req.url());
+ if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
+ if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
+ if (url.pathname === "/api/state") return route.fulfill({ json: { agents: [], profiles: [], settings: { lang, theme: "light" } } });
+ if (url.pathname === "/api/plugins") return route.fulfill({ json: { plugins: [] } });
+ if (url.pathname === "/api/library") return route.fulfill({ json: lib });
+ if (url.pathname === "/api/library/mcp/check") return route.fulfill({ json: { servers: {} } });
+ if (url.pathname === "/api/library/servers/save") {
+ const { old, server: s } = req.postDataJSON();
+ calls.push(s.name + " " + s.startupTimeout);
+ const i = lib.servers.findIndex((x) => x.name === old);
+ lib.servers[i] = { ...lib.servers[i], ...s };
+ if (!s.startupTimeout) delete lib.servers[i].startupTimeout;
+ return route.fulfill({ json: { ...lib, result: { changed: agents.map((a) => a.id) } } });
+ }
+ if (url.pathname === "/api/usage/quotas") return route.fulfill({ json: [] });
+ if (url.pathname === "/api/groups") return route.fulfill({ json: { groups: [] } });
+ if (url.pathname === "/api/providers") return route.fulfill({ json: { providers: [], gateway: { running: true } } });
+ if (url.pathname.startsWith("/api/")) return route.fulfill({ json: {} });
+ const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
+ const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
+ await route.fulfill({ body: await fs.readFile(file), contentType });
+ };
+}
+
+for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
+ test(engine + ": an MCP server's startup timeout, for Codex", async (t) => {
+ assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit");
+ const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: process.env.PLAYWRIGHT_CHANNEL || "chromium" }));
+ const errors = [];
+ t.after(async () => {
+ if (errors.length) console.log(errors);
+ await browser.close();
+ });
+ for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) {
+ for (const width of [1100, 390]) {
+ await t.test(`${lang} ${width}`, async () => {
+ const w = (s, v) => tr(lang, s, v);
+ const go = async (agents) => {
+ const calls = [];
+ const ctx = await browser.newContext({ viewport: { width, height: 800 } });
+ await ctx.addInitScript(() => { try { localStorage.setItem("magpie.libTab", "mcp"); } catch {} });
+ const page = await ctx.newPage();
+ page.setDefaultTimeout(5000);
+ page.on("pageerror", (e) => errors.push(e.message));
+ await page.route("**/*", server(lang, calls, agents));
+ await page.goto("http://magpie.test/");
+ await page.locator('button[data-view="library"]').click();
+ const row = page.locator("#view-library .lib-server", { has: page.locator('.lib-health[data-server="slow"]') });
+ const ed = page.locator("#modal .lib-editor");
+ const open = async () => { await row.locator(".name").click(); await ed.waitFor(); };
+ const save = async () => { await ed.locator(":scope > .bar button.primary").click(); await ed.waitFor({ state: "detached" }); };
+ return { ctx, page, ed, calls, open, save, wait: ed.getByLabel(w("Startup timeout"), { exact: true }) };
+ };
+
+ // no agent that takes one: no field
+ {
+ const { ctx, ed, open, wait } = await go([agent("claude", "Claude Code")]);
+ await open();
+ await ed.getByText(w("Agents"), { exact: true }).first().waitFor();
+ assert.equal(await wait.count(), 0, "a startup timeout with no Codex here");
+ await ctx.close();
+ }
+
+ const { ctx, page, ed, calls, open, save, wait } = await go([agent("claude", "Claude Code"), { ...agent("codex", "Codex"), startup: true }]);
+ // empty: Codex's own; the hint names Codex and that a hand-written value stays
+ await open();
+ assert.equal(await wait.inputValue(), "");
+ assert.equal(await wait.getAttribute("placeholder"), "30");
+ await ed.locator(".hint", { hasText: w("Seconds {agents} waits for it to start and list its tools. Empty leaves {agents}'s own 30; a value you wrote in its config.toml by hand is kept", { agents: "Codex" }) }).waitFor();
+ // digits only, saved with the server
+ await wait.pressSequentially("1a20");
+ assert.equal(await wait.inputValue(), "120");
+ await save();
+ assert.deepEqual(calls, ["slow 120"]);
+ // shown again; emptied, saved as the agent's own
+ await open();
+ assert.equal(await wait.inputValue(), "120");
+ await wait.fill("");
+ await save();
+ assert.deepEqual(calls, ["slow 120", "slow 0"]);
+ assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), true, "no sideways scroll");
+ await ctx.close();
+ });
+ }
+ }
+ assert.deepEqual(errors, []);
+ });
+}
diff --git a/internal/library/library.go b/internal/library/library.go
index 92df36f1a..54ab2ea03 100644
--- a/internal/library/library.go
+++ b/internal/library/library.go
@@ -104,6 +104,10 @@ type Applied struct {
// Subagents are the files magpie wrote for the subagents, each with
// the hash of what it wrote: one changed since is the user's
Subagents []SubagentFile `json:"subagents,omitempty"`
+ // Startup is, for each server, the startup timeout magpie wrote in its
+ // entry (Codex's startup_timeout_sec): one there other than this is
+ // the user's
+ Startup map[string]float64 `json:"startup,omitempty"`
}
var mu lock // one change at a time, from the page or the CLI's process
diff --git a/internal/library/mcp.go b/internal/library/mcp.go
index e54eea19f..26094add5 100644
--- a/internal/library/mcp.go
+++ b/internal/library/mcp.go
@@ -47,6 +47,15 @@ type Server struct {
// (GitHub's, 新v学员 on Discord). It is magpie's alone: the agents are
// given the server as before.
OAuth *OAuthApp `json:"oauth,omitempty"`
+ // StartupTimeout is the seconds an agent waits for the server to start
+ // and list its tools: Codex's startup_timeout_sec (#3168), the only
+ // agent given it. 0 leaves it to the agent (Codex's own is 30s).
+ StartupTimeout int `json:"startupTimeout,omitempty"`
+
+ // startupWrote is the startup_timeout_sec magpie last wrote in the
+ // entry being written, 0 for none: one the entry has otherwise is the
+ // user's, and stays (startupTheirs)
+ startupWrote float64
}
// OAuthApp is an OAuth app made with a server's vendor, by the names
@@ -117,6 +126,9 @@ func (s *Server) check() error {
s.OAuth = nil
}
}
+ if s.StartupTimeout < 0 || s.StartupTimeout > maxStartupTimeout {
+ return fmt.Errorf("%s: the startup timeout is between 0 (the agent's own) and %d seconds", s.Name, maxStartupTimeout)
+ }
for k := range s.Env {
if strings.TrimSpace(k) == "" {
delete(s.Env, k)
@@ -345,15 +357,69 @@ func selfTimeout(s *Server, def int) int {
return def
}
+// maxStartupTimeout is the longest startup timeout a server is given: a
+// day, as a hook's timeout.
+const maxStartupTimeout = 86400
+
+// startupTheirs says whether old, a Codex entry, has a startup timeout
+// magpie didn't write: a startup_timeout_ms (magpie writes only _sec, and
+// Codex reads _ms only without it), or a startup_timeout_sec other than
+// the one magpie wrote last. That one is the user's, and magpie's value
+// never goes over it.
+func startupTheirs(s *Server, old map[string]any) bool {
+ if _, ok := old["startup_timeout_ms"]; ok {
+ return true
+ }
+ v, ok := old["startup_timeout_sec"]
+ return ok && (s.startupWrote == 0 || !isNumber(v, s.startupWrote))
+}
+
+// startupWritten is the startup_timeout_sec of magpie's in the entry it
+// writes for s over old, for the next write to know it by: 0 for none.
+func (f *mcpFile) startupWritten(s *Server, old map[string]any) float64 {
+ if f.Format != fmtCodex || startupTheirs(s, old) {
+ return 0
+ }
+ return float64(s.StartupTimeout)
+}
+
+// startupBehind says whether a Codex entry lacks the startup timeout
+// magpie gives s, or has one magpie wrote that s no longer has.
+func startupBehind(s *Server, old map[string]any) bool {
+ if startupTheirs(s, old) {
+ return false
+ }
+ v, ok := old["startup_timeout_sec"]
+ if s.StartupTimeout == 0 {
+ return ok
+ }
+ return !isNumber(v, float64(s.StartupTimeout))
+}
+
+// wroteStartup is s with the startup timeout magpie last wrote in its
+// entry.
+func wroteStartup(s *Server, v float64) *Server {
+ if s.startupWrote == v {
+ return s
+ }
+ c := *s
+ c.startupWrote = v
+ return &c
+}
+
// gooseOldTimeout is the timeout magpie wrote for every Goose server before
// magpie-image was given a longer one.
const gooseOldTimeout = 300
// behind says whether an entry magpie wrote before lacks the timeout it
// gives s now: Codex's tool_timeout_sec is missing, or Goose's timeout is
-// still the gooseOldTimeout every server had. A value the user chose is
-// neither, so it is left as it is.
+// still the gooseOldTimeout every server had, or Codex's startup timeout
+// isn't the one s has (startupBehind). A value the user chose is none of
+// these, so it is left as it is.
func (f *mcpFile) behind(s *Server, old map[string]any) bool {
+ if f.Format == fmtCodex && old != nil && startupBehind(s, old) {
+ return true
+ }
if selfTimeout(s, 0) == 0 {
return false
}
@@ -631,6 +697,10 @@ func (f *mcpFile) encode(s *Server) ordered {
if t := selfTimeout(s, 0); t > 0 {
add("tool_timeout_sec", t)
}
+ // and 30s to start and list its tools unless its entry says more
+ if s.StartupTimeout > 0 {
+ add("startup_timeout_sec", s.StartupTimeout)
+ }
case fmtDsh:
// a reference is a !!js expression dsh evaluates (dshRef)
add("serverName", s.Name)
@@ -1094,6 +1164,16 @@ func (f *mcpFile) merged(s *Server, old map[string]any) ordered {
o := f.encode(s)
mine := f.mine(s)
behind := f.behind(s, old)
+ // Codex's startup timeout is magpie's unless the user wrote one
+ // (startupTheirs): theirs is kept as it is, below, with no _sec of
+ // magpie's beside a _ms of theirs
+ if f.Format == fmtCodex {
+ if startupTheirs(s, old) {
+ o = slices.DeleteFunc(o, func(e kv) bool { return e.k == "startup_timeout_sec" })
+ } else {
+ mine = append(slices.Clone(mine), "startup_timeout_sec")
+ }
+ }
for i, e := range o {
if v, ok := old[e.k]; ok && !slices.Contains(mine, e.k) && !(behind && f.Format == fmtGoose && e.k == "timeout") {
o[i].v = v
diff --git a/internal/library/mcp_startup_test.go b/internal/library/mcp_startup_test.go
new file mode 100644
index 000000000..f5a74561a
--- /dev/null
+++ b/internal/library/mcp_startup_test.go
@@ -0,0 +1,150 @@
+package library
+
+import (
+ "path/filepath"
+ "strings"
+ "testing"
+
+ toml "github.com/pelletier/go-toml/v2"
+)
+
+// codexEntry is the server's entry in a Codex config.toml.
+func codexEntry(t *testing.T, path, name string) map[string]any {
+ t.Helper()
+ var doc map[string]any
+ if err := toml.Unmarshal([]byte(read(t, path)), &doc); err != nil {
+ t.Fatal(err)
+ }
+ m, _ := doc["mcp_servers"].(map[string]any)
+ e, _ := m[name].(map[string]any)
+ return e
+}
+
+// A server's startup timeout reaches Codex as startup_timeout_sec, follows
+// the library when it changes, and goes when it is taken off; no other
+// agent is given it (#3168).
+func TestCodexStartupTimeout(t *testing.T) {
+ h := sandbox(t)
+ cfg := filepath.Join(h, ".codex/config.toml")
+ srv := Server{Name: "slow", Transport: "stdio", Command: "npx", Args: []string{"-y", "slow-mcp"}, Agents: []string{"claude", "codex"}}
+
+ ok(t)(SaveServer("", srv))
+ if e := codexEntry(t, cfg, "slow"); e == nil || e["startup_timeout_sec"] != nil {
+ t.Fatalf("no timeout set, yet Codex has one:\n%s", read(t, cfg))
+ }
+
+ for _, n := range []int{120, 45} {
+ srv.StartupTimeout = n
+ ok(t)(SaveServer("slow", srv))
+ if e := codexEntry(t, cfg, "slow"); !isNumber(e["startup_timeout_sec"], float64(n)) {
+ t.Fatalf("startup_timeout_sec = %v, want %d:\n%s", e["startup_timeout_sec"], n, read(t, cfg))
+ }
+ }
+ if s := read(t, filepath.Join(h, ".claude.json")); strings.Contains(s, "startup") || strings.Contains(s, "45") {
+ t.Errorf("Claude Code was given the startup timeout:\n%s", s)
+ }
+
+ srv.StartupTimeout = 0
+ ok(t)(SaveServer("slow", srv))
+ if e := codexEntry(t, cfg, "slow"); e == nil || e["startup_timeout_sec"] != nil {
+ t.Errorf("the timeout taken off stays in Codex:\n%s", read(t, cfg))
+ }
+
+ srv.StartupTimeout = -1
+ if _, err := SaveServer("slow", srv); err == nil {
+ t.Error("a negative startup timeout was saved")
+ }
+ srv.StartupTimeout = maxStartupTimeout + 1
+ if _, err := SaveServer("slow", srv); err == nil {
+ t.Error("a startup timeout over a day was saved")
+ }
+}
+
+// A startup timeout the user wrote in Codex's config.toml by hand is never
+// written over: one there before magpie had any, one changed by hand after
+// magpie wrote its own, and Codex's older startup_timeout_ms. Once the
+// user's is taken out, magpie's goes in.
+func TestCodexStartupTimeoutKeepsUsers(t *testing.T) {
+ h := sandbox(t)
+ cfg := filepath.Join(h, ".codex/config.toml")
+ srv := Server{Name: "slow", Transport: "stdio", Command: "npx", Agents: []string{"codex"}}
+ ok(t)(SaveServer("", srv))
+ hand := func(from, to string) {
+ t.Helper()
+ s := read(t, cfg)
+ if !strings.Contains(s, from) {
+ t.Fatalf("no %q in:\n%s", from, s)
+ }
+ write(t, cfg, strings.Replace(s, from, to, 1))
+ }
+ want := func(key string, n float64) {
+ t.Helper()
+ e := codexEntry(t, cfg, "slow")
+ if !isNumber(e[key], n) {
+ t.Fatalf("%s = %v, want %v:\n%s", key, e[key], n, read(t, cfg))
+ }
+ }
+
+ // the user's before magpie had one
+ hand("command = ", "startup_timeout_sec = 90\ncommand = ")
+ srv.StartupTimeout = 20
+ ok(t)(SaveServer("slow", srv))
+ want("startup_timeout_sec", 90)
+ if n := strings.Count(read(t, cfg), "startup_timeout_sec"); n != 1 {
+ t.Fatalf("%d startup_timeout_sec:\n%s", n, read(t, cfg))
+ }
+
+ // taken out by hand: magpie's goes in, and follows the library
+ hand("startup_timeout_sec = 90\n", "")
+ ok(t)(Sync())
+ want("startup_timeout_sec", 20)
+ srv.StartupTimeout = 25
+ ok(t)(SaveServer("slow", srv))
+ want("startup_timeout_sec", 25)
+
+ // magpie's changed by hand is the user's from then on
+ hand("startup_timeout_sec = 25", "startup_timeout_sec = 75")
+ srv.StartupTimeout = 30
+ ok(t)(SaveServer("slow", srv))
+ want("startup_timeout_sec", 75)
+ srv.StartupTimeout = 0
+ ok(t)(SaveServer("slow", srv))
+ want("startup_timeout_sec", 75)
+
+ // Codex reads startup_timeout_ms only without _sec: magpie writes no
+ // _sec beside the user's _ms
+ hand("startup_timeout_sec = 75", "startup_timeout_ms = 40000")
+ srv.StartupTimeout = 20
+ ok(t)(SaveServer("slow", srv))
+ e := codexEntry(t, cfg, "slow")
+ if e["startup_timeout_sec"] != nil || !isNumber(e["startup_timeout_ms"], 40000) {
+ t.Errorf("the user's startup_timeout_ms isn't what Codex reads:\n%s", read(t, cfg))
+ }
+}
+
+// A project's .codex/config.toml is given the startup timeout too, and
+// follows it when it changes.
+func TestCodexProjectStartupTimeout(t *testing.T) {
+ sandbox(t)
+ proj := filepath.Join(t.TempDir(), "app")
+ write(t, filepath.Join(proj, "README"), "app\n")
+ ok(t)(AddProject(proj))
+ srv := Server{Name: "slow", Transport: "stdio", Command: "npx", StartupTimeout: 60}
+ ok(t)(SaveServer("", srv))
+ ok(t)(ProjectServer(proj, "slow", []string{"codex"}))
+ cfg := filepath.Join(proj, ".codex/config.toml")
+ if e := codexEntry(t, cfg, "slow"); !isNumber(e["startup_timeout_sec"], 60) {
+ t.Fatalf("project:\n%s", read(t, cfg))
+ }
+ srv.StartupTimeout = 15
+ ok(t)(SaveServer("slow", srv))
+ if e := codexEntry(t, cfg, "slow"); !isNumber(e["startup_timeout_sec"], 15) {
+ t.Fatalf("project didn't follow the library:\n%s", read(t, cfg))
+ }
+ write(t, cfg, strings.Replace(read(t, cfg), "startup_timeout_sec = 15", "startup_timeout_sec = 300", 1))
+ srv.StartupTimeout = 10
+ ok(t)(SaveServer("slow", srv))
+ if e := codexEntry(t, cfg, "slow"); !isNumber(e["startup_timeout_sec"], 300) {
+ t.Fatalf("project's hand-written timeout was written over:\n%s", read(t, cfg))
+ }
+}
diff --git a/internal/library/project_mcp.go b/internal/library/project_mcp.go
index f68d18c58..b2f372c6f 100644
--- a/internal/library/project_mcp.go
+++ b/internal/library/project_mcp.go
@@ -5,6 +5,7 @@ import (
"encoding/json"
"errors"
"fmt"
+ "maps"
"os"
"path/filepath"
"slices"
@@ -139,6 +140,7 @@ func (l *Library) syncProjectMCP(p *Project, fail func(what string, err error))
files[rel] = true
}
wrote := map[string][]string{}
+ startup := map[string]map[string]float64{}
for _, rel := range slices.Sorted(func(yield func(string) bool) {
for r := range files {
if !yield(r) {
@@ -153,11 +155,16 @@ func (l *Library) syncProjectMCP(p *Project, fail func(what string, err error))
abs := filepath.Join(p.Dir, filepath.FromSlash(rel))
f := &mcpFile{Path: abs, Format: format}
had := p.Wrote[rel]
+ was := p.Startup[rel]
+ now := map[string]float64{}
entries, err := f.entries()
if err != nil {
fail("", err)
if len(had) > 0 {
wrote[rel] = had
+ if was != nil {
+ startup[rel] = was
+ }
}
continue
}
@@ -172,9 +179,11 @@ func (l *Library) syncProjectMCP(p *Project, fail func(what string, err error))
if err := f.del(name); err != nil {
fail("mcp:"+name, err)
mine = append(mine, name)
+ now[name] = was[name]
}
}
for _, s := range want[rel] {
+ s := wroteStartup(s, was[s.Name])
old := entries[s.Name]
if old != nil && !slices.Contains(had, s.Name) {
fail("mcp:"+s.Name, fmt.Errorf("%s has a server called %s already that isn't magpie's: it's left as it is", rel, s.Name))
@@ -183,6 +192,7 @@ func (l *Library) syncProjectMCP(p *Project, fail func(what string, err error))
if old != nil {
if cur, ok := f.current(s.Name, old, s); ok && cur.same(s) && !f.behind(s, old) {
mine = append(mine, s.Name)
+ now[s.Name] = f.startupWritten(s, old)
continue
}
}
@@ -199,12 +209,18 @@ func (l *Library) syncProjectMCP(p *Project, fail func(what string, err error))
fail("mcp:"+s.Name, err)
if old != nil {
mine = append(mine, s.Name)
+ now[s.Name] = was[s.Name]
}
continue
}
mine = append(mine, s.Name)
+ now[s.Name] = f.startupWritten(s, old)
}
sort.Strings(mine)
+ maps.DeleteFunc(now, func(_ string, v float64) bool { return v == 0 })
+ if len(now) > 0 {
+ startup[rel] = now
+ }
if len(mine) > 0 {
wrote[rel] = mine
continue
@@ -225,6 +241,10 @@ func (l *Library) syncProjectMCP(p *Project, fail func(what string, err error))
wrote = nil
}
p.Wrote = wrote
+ if len(startup) == 0 {
+ startup = nil
+ }
+ p.Startup = startup
sort.Strings(p.MadeFiles)
}
diff --git a/internal/library/projects.go b/internal/library/projects.go
index b9b04854a..220848ec9 100644
--- a/internal/library/projects.go
+++ b/internal/library/projects.go
@@ -37,6 +37,10 @@ type Project struct {
// Wrote are, by the project's file (.mcp.json), the servers magpie
// wrote in it, the only entries it ever takes out
Wrote map[string][]string `json:"wrote,omitempty"`
+ // Startup are, by the project's file, the startup timeout magpie
+ // wrote in each server's entry there (Codex's startup_timeout_sec):
+ // one other than this is the user's
+ Startup map[string]map[string]float64 `json:"startup,omitempty"`
// MadeFiles are the files magpie made to write servers in, listed in
// the .gitignore and taken away again once nothing's left in them
MadeFiles []string `json:"madeFiles,omitempty"`
diff --git a/internal/library/sync.go b/internal/library/sync.go
index 9618c66ed..26dbf66e7 100644
--- a/internal/library/sync.go
+++ b/internal/library/sync.go
@@ -181,6 +181,7 @@ func (l *Library) syncMCP(t *Target, b *backups, res *Result) {
}
how := toolsOffOf(t)
toolsOff := map[string][]string{} // what magpie's in each entry's list now
+ startup := map[string]float64{} // the startup timeout magpie's in each entry now
entries, err := t.MCP.entries()
if err != nil {
res.fail(id, "mcp", err)
@@ -208,6 +209,7 @@ func (l *Library) syncMCP(t *Target, b *backups, res *Result) {
if _, ok := entries[name]; (ok || t.MCP.holds(name)) && !write("mcp:"+name, func() error { return t.MCP.del(name) }) {
mine = append(mine, name)
toolsOff[name] = a.ToolsOff[name]
+ startup[name] = a.Startup[name]
}
}
base := gatewayOf(t)
@@ -221,6 +223,7 @@ func (l *Library) syncMCP(t *Target, b *backups, res *Result) {
if slices.Contains(a.MCP, s.Name) {
mine = append(mine, s.Name)
toolsOff[s.Name] = a.ToolsOff[s.Name]
+ startup[s.Name] = a.Startup[s.Name]
}
continue
}
@@ -230,6 +233,7 @@ func (l *Library) syncMCP(t *Target, b *backups, res *Result) {
continue
}
s, _ = t.MCP.side(s)
+ s = wroteStartup(s, a.Startup[s.Name])
old := entries[s.Name]
if err := t.MCP.foreign(old); err != nil {
res.fail(id, "mcp:"+s.Name, err)
@@ -250,17 +254,29 @@ func (l *Library) syncMCP(t *Target, b *backups, res *Result) {
if cur, ok := t.MCP.current(s.Name, old, s); ok && cur.same(s) && t.MCP.has(s) && !t.MCP.behind(s, old) {
mine = append(mine, s.Name)
toolsOff[s.Name] = offMine
+ startup[s.Name] = t.MCP.startupWritten(s, old)
continue
}
}
if write("mcp:"+s.Name, func() error { return t.MCP.putEntry(s, off.apply(t.MCP.merged(s, old))) }) {
mine = append(mine, s.Name)
toolsOff[s.Name] = offMine
+ startup[s.Name] = t.MCP.startupWritten(s, old)
} else if old != nil {
toolsOff[s.Name] = prev // the entry is as it was
+ startup[s.Name] = a.Startup[s.Name]
}
}
a.MCP = mine
+ for k, v := range startup {
+ if v == 0 || !slices.Contains(mine, k) {
+ delete(startup, k)
+ }
+ }
+ a.Startup = startup
+ if len(a.Startup) == 0 {
+ a.Startup = nil
+ }
for k, v := range toolsOff {
if len(v) == 0 {
delete(toolsOff, k)
@@ -300,8 +316,11 @@ type AgentView struct {
NoEnvRefs bool `json:"noEnvRefs,omitempty"`
// ToolsOff: it can be told to leave out single tools of a server
// (mcp_tools_off.go); the page names those that can't
- ToolsOff bool `json:"toolsOff,omitempty"`
- MCPVia string `json:"mcpVia,omitempty"`
+ ToolsOff bool `json:"toolsOff,omitempty"`
+ // Startup: it is given a server's startup timeout (Codex's
+ // startup_timeout_sec)
+ Startup bool `json:"startup,omitempty"`
+ MCPVia string `json:"mcpVia,omitempty"`
// How is the way it is given its skills, link or copy, and HowOwn its
// own over the library's; MustCopy is one that can only take copies
// (in WSL)
@@ -433,6 +452,7 @@ func readView(problems []Problem, glance bool) (*View, error) {
av.NoRemote = t.MCP.supports(&Server{Transport: "http"}) != nil
av.NoEnvRefs = t.MCP.refsOf() == envSyntax{}
av.ToolsOff = toolsOffOf(t) != toolsNone
+ av.Startup = t.MCP.Format == fmtCodex
}
v.Agents = append(v.Agents, av)
}
diff --git a/internal/tui/library.go b/internal/tui/library.go
index bc2527e1b..7a4b709b9 100644
--- a/internal/tui/library.go
+++ b/internal/tui/library.go
@@ -416,8 +416,8 @@ func saveServer(old *library.Server, line string) tea.Cmd {
was, done := "", "added "+s.Name+" · ↵ on it gives it to agents"
if old != nil {
was, done = old.Name, "saved "+s.Name
- // and its OAuth app, which only the GUI edits
- s.Agents, s.Env, s.Headers, s.OAuth = old.Agents, old.Env, old.Headers, old.OAuth
+ // and its OAuth app and startup timeout, which only the GUI edits
+ s.Agents, s.Env, s.Headers, s.OAuth, s.StartupTimeout = old.Agents, old.Env, old.Headers, old.OAuth, old.StartupTimeout
}
return libCmd(func() (*library.Result, error) { return library.SaveServer(was, s) }, done)()
}