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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions .changeset/24191-serve-mcp-stdio-early-initialize.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
---
'@objectstack/cli': patch
---

Clause-②: no

fix(cli): `os serve` with the stdio MCP transport and no config argument answers the `initialize` an MCP client writes when it spawns the server, and boots the configured app

- **What was wrong.** An MCP client writes `initialize` to the server's stdin as soon as it spawns it. The CLI's argument parser fills an omitted positional argument from a pending stdin line, and `os serve`'s config path is an optional positional. So, started without a config path, `os serve` took the client's `initialize` as its config path. In a project with a compiled `dist/objectstack.json`, it printed `No objectstack.config.ts found — booting from artifact`, booted without the config's own plugins, and never answered `initialize`. `os start` already named the path when it started `os serve`; this is the same defect for `os serve` started directly.
- **What changed.** `os serve` no longer reads its config path from stdin. Without the argument it uses `objectstack.config.ts` in the working directory, as its help says, and the client's first message stays in the pipe for the stdio transport. Reading the config path from stdin was never documented, and no script, test or doc in this repository relied on it; to serve another config, pass its path as the argument.
- **Unchanged:** the flags and environment variables of `os serve`, and which config and artifact a boot uses when the path is given or when nothing waits on stdin.
8 changes: 7 additions & 1 deletion packages/cli/src/commands/serve.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1397,7 +1397,13 @@ export default class Serve extends Command {
static override description = 'Start ObjectStack server. Reads `objectstack.config.ts` if present; otherwise falls back to `dist/objectstack.json` (or OS_ARTIFACT_PATH, including http(s):// URLs) as a portable artifact.';

static override args = {
config: Args.string({ description: 'Configuration file path', required: false, default: 'objectstack.config.ts' }),
// [#24191] `ignoreStdin`: oclif otherwise fills an omitted positional from
// a line already waiting on stdin (`tryStdin`), and with the stdio MCP
// transport that line is the client's `initialize`, written at spawn. It
// became the config path, the boot fell back to the artifact without the
// config, and the request was never answered. Stdin belongs to the
// transport; the config path comes from argv or the default.
config: Args.string({ description: 'Configuration file path', required: false, default: 'objectstack.config.ts', ignoreStdin: true }),
};

static override flags = {
Expand Down
72 changes: 65 additions & 7 deletions packages/cli/test/serve-mcp-stdio-answers.e2e.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,21 @@
* `readableFlowing` is `null` — never after an explicit `pause()`. Listener
* attached, `bytesRead` 0, server deaf.
*
* WHY THIS FILE NOW PAUSES STDIN ITSELF (#24191). `serve` no longer supplies
* that pause: its `config` positional sets `ignoreStdin`, because oclif's
* stdin read also SWALLOWED an `initialize` the client wrote at spawn (pinned in
* `serve-mcp-stdio-early-initialize.integration.test.ts`). The `resume()` in
* `MCPServerRuntime.start()` stays, for the reason its own comment gives: any
* host that touched stdin before `start()` — a readline prompt, a supervisor,
* an embedding process — leaves it paused. Without a pauser this file stayed
* green with that `resume()` removed (measured on the #24191 change), so the
* stdio boot now runs with a preload that IS such a host
* (`PAUSE_STDIN_FIRST`): it pauses `process.stdin` before the CLI loads, and
* reports `readableFlowing` at the moment the transport attaches its `data`
* listener. The test asserts that report reads `false`, so the premise is
* measured on every run rather than assumed, and a later change that resumes
* stdin earlier cannot quietly make this file vacuous again.
*
* WHY THIS FILE SPAWNS THE CLI. `packages/mcp`'s 17 existing stdio pins were
* all green while every real `os serve` stdio session was unusable, because
* they sit BELOW the gap: they exercise the runtime in a plain node process,
Expand All @@ -30,7 +45,8 @@
* the mechanism, not the consequence. The assertion below is the card's own
* repro: write a real `initialize` to the child's stdin, get a real result
* back. Reverse-verified — with the `resume()` in `MCPServerRuntime.start()`
* removed, this file times out with zero bytes on stdout.
* removed, this file times out with zero bytes on stdout (re-measured with the
* preload above when #24191 moved the pause out of `serve`).
*
* WHY IT MINTS A KEY OVER HTTP FIRST. stdio auto-start is fail-closed
* (ADR-0101): without an `OS_MCP_STDIO_API_KEY` that resolves to a real
Expand Down Expand Up @@ -93,6 +109,30 @@ const HERE = resolve(fileURLToPath(import.meta.url), '..');
*/
const CLI = resolve(HERE, '../bin/run.js');

/** The line the preload prints each time a `data` listener attaches to stdin. */
const PREMISE_TAG = '[fx-7645] stdin data listener attached, readableFlowing=';

/**
* Node arguments for the stdio boot: a host that paused stdin before the CLI
* loaded — #7645's premise, which `serve` itself no longer supplies (#24191).
*
* `process.stdin.pause()` is what readline's `Interface.close()` did when
* oclif's `tryStdin` paused it. The `newListener` report fires BEFORE the
* listener is added, so it reads the state the transport's `data` listener
* meets: `false` is the premise holding, `null` is a stream nobody paused.
* A `data:` URL keeps the whole host on this page; `--import` runs it before
* `bin/run.js`.
*/
const PAUSE_STDIN_FIRST: readonly string[] = [
'--import',
`data:text/javascript,${encodeURIComponent([
'process.stdin.pause();',
"process.stdin.on('newListener', (event) => {",
` if (event === 'data') process.stderr.write(${JSON.stringify(PREMISE_TAG)} + String(process.stdin.readableFlowing) + '\\n');`,
'});',
].join('\n'))}`,
];

const CONFIG = `
export default {
manifest: {
Expand Down Expand Up @@ -134,14 +174,19 @@ interface Booted {
* stdout alone would wait on a stream that carries nothing until a client
* speaks.
*
* NOTE: no positional config path is passed. That is deliberate and load-bearing:
* supplying one makes oclif skip `tryStdin` entirely, so stdin is never paused
* and the defect cannot reproduce. `os serve --dev` is also the form every user
* types.
* NOTE: no positional config path is passed. That used to be what paused stdin
* (oclif's `tryStdin` ran only for an omitted positional); since #24191 `serve`
* never reads stdin for it either way, and the pause comes from `nodeArgs`
* (`PAUSE_STDIN_FIRST`). The bare form stays because `os serve --dev` is the
* form every user types.
*/
function boot(env: Record<string, string | undefined>, waitFor: RegExp): Promise<Booted> {
function boot(
env: Record<string, string | undefined>,
waitFor: RegExp,
nodeArgs: readonly string[] = [],
): Promise<Booted> {
return new Promise((resolveBoot, rejectBoot) => {
const child = spawn(process.execPath, [CLI, 'serve', '-p', port, '--dev'], {
const child = spawn(process.execPath, [...nodeArgs, CLI, 'serve', '-p', port, '--dev'], {
cwd: dir,
stdio: ['pipe', 'pipe', 'pipe'],
// `childEnv`, not a bare `...process.env`: the vitest worker exports
Expand Down Expand Up @@ -423,8 +468,21 @@ describe('#7645: the stdio MCP transport answers over a spawned CLI process', ()
OS_MCP_STDIO_API_KEY: apiKey,
},
/\[MCP\] Server started \(transport: stdio/,
PAUSE_STDIN_FIRST,
);

// The premise, measured: the transport attached its reader to a stdin that
// was already paused, so only `resume()` can make it flow. Every attach the
// preload saw reads `false`; none at all means the preload never ran.
const attaches = booted.stderr()
.split('\n')
.filter((line) => line.includes(PREMISE_TAG))
.map((line) => line.slice(line.indexOf(PREMISE_TAG) + PREMISE_TAG.length).trim());
expect(
attaches.length > 0 && attaches.every((state) => state === 'false'),
`stdin was not paused when the transport attached (readableFlowing at each data-listener attach: ${JSON.stringify(attaches)}), so this run never exercised #7645's resume()\n--- stderr ---\n${booted.stderr().slice(-4000)}`,
).toBe(true);

// The started transport is the premise, not the assertion — the whole
// defect was a transport that reached exactly this line and then went deaf.
const reply = await new Promise<string | null>((resolveReply) => {
Expand Down
Loading
Loading