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
3 changes: 2 additions & 1 deletion pkgs/mcpx/docs/compare/register/code-mode.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ Status column: **mcpx @ 05c78b2**. Legend and citation conventions: [../README.m
| CODE-13 | Progress token requested so long calls outlive the timeout | `opencode v1 has` `opencode v2 has` `mcpx missing` | v1 token and reset · v2 token, no reset · lootbox, mcpx none | partial — sends a token when the host did and relays progress (#212); the daemon's own timeout does not reset on it | + med | S | med |
| CODE-14 | CPU-time and subrequest caps per invocation | `does not match mcpx's goal` | CF `cpuMs`, `subRequests` · others wall clock only | n/a — wall clock only | − marginal | M | low |
| CODE-15 | Tool-call budget per execution | `opencode v1 has` `opencode v2 has` | v1/v2 knob, unset by host · lootbox, mcpx, CF none | ✗ — only the timeout bounds a looping script | + low | S | low |
| CODE-16 | Cap on the size of returned output | `opencode v1 has` `opencode v2 has` `mcpx missing` | v1/v2 knob · CF 6,000 tokens · lootbox, mcpx whole stdout | ✗ — stdout returned whole; only stderr is bounded (#216) | + high | S | med |
| CODE-16 | Cap on the size of returned output | `opencode v1 has` `opencode v2 has` `mcpx has` | v1/v2 knob · CF 6,000 tokens · lootbox whole stdout, mcpx capped at `exec.maxOutputBytes` | ✓ — returned stdout capped at the execsvc Result boundary (default 64KiB): head kept, in-band marker names dropped bytes, `stdoutTruncated` set; full record unchanged (#1937) | + high | S | med |
| CODE-17 | Concurrent tool calls within one program | `opencode v1 has` | v1 8 · v2 unrestricted · lootbox, mcpx, CF no cap | n/a — per-server pool max 4, no per-run cap | + low | S | low |
| CODE-18 | Upstream call cancelled when the script times out or dies | `has better replacement` | mcpx ✓ · v1/v2 ✓ · lootbox ✗ · CF unverified | ✓ — context cancel sends `notifications/cancelled` | + low | S | low |
| CODE-19 | Final top-level expression becomes the result | `opencode v2 has` `mcpx missing` | v2 ✓ · CF ✓ · v1 `null` · lootbox none · mcpx stdout | ✗ — result is stdout, `emit()` or a default export (#216) | + med | M | low |
Expand Down Expand Up @@ -441,6 +441,7 @@ Status column: **mcpx @ 05c78b2**. Legend and citation conventions: [../README.m
the whole envelope; plugin-API register, PLG-40), floods the caller's context, which is exactly what code mode exists
to prevent.
- **Effort.** S — an `exec.maxOutputBytes` setting that truncates with a marker and sets `truncated`.
- **As built (#1937, 2026-10-31).** Landed as specified: setting `exec.maxOutputBytes` (KindBytes, default `64KiB`, defaults.json `exec.stdoutLimit` following the `stderrLimit` pattern), wired into `execsvc.Limits.StdoutLimit` by both the daemon (`/v1/exec`) and the CLI local path. The cap is applied once, at the end of `execsvc.Service.Run` where the `Result` is handed back, so every returning surface sees the same capped `Stdout`: the head is kept (UTF-8-boundary safe), the returned string never exceeds the cap, it ends with a marker naming kept/total/dropped bytes, and `Result.StdoutTruncated` (`stdoutTruncated`) is set. Internal consumers (the JSON answer parse, hooks) still see the full text, and the full output is unchanged wherever a full record already exists. 0 disables the cap. Tests: `internal/execsvc/stdout_limit_test.go` (over-cap capped+marker, under-cap and exact-cap byte-identical, 0 disables, UTF-8 boundary).
- **Risk.** Without it, one chatty script can cost more tokens than the direct call it replaced.
- **Detail.** v1's README tells hosts without their own truncation to set it, "or oversized results silently flood model
context" (`v1:packages/codemode/README.md:268`). v2 gives warnings a separate budget equal to `maxOutputBytes`
Expand Down
3 changes: 2 additions & 1 deletion pkgs/mcpx/docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -411,6 +411,7 @@ and a switch to turn the report off would have kept it quiet.

| setting | kind | default | scope | hot | flag | variable | governs |
| --- | --- | --- | --- | --- | --- | --- | --- |
| `exec.maxOutputBytes` | bytes | `64KiB` | call | yes | `--exec-max-output-bytes` | `MCPX_EXEC_MAX_OUTPUT_BYTES` | cap the stdout a run returns, with a truncation marker |
| `exec.output` | enum | `text` | call | yes | `--exec-output`, `--output` | `MCPX_EXEC_OUTPUT` | text for a terminal, structured for one document, stream for frames |
| `exec.timeout` | duration | `120s` | call | yes | `--exec-timeout` | `MCPX_EXEC_TIMEOUT` | kill a script after this long |
| `exec.where` | enum | `auto` | call | yes | `--exec-where` | `MCPX_EXEC_WHERE` | in this process, or on the daemon |
Expand Down Expand Up @@ -695,7 +696,7 @@ and a switch to turn the report off would have kept it quiet.
| setting | kind | default | scope | hot | flag | variable | governs |
| --- | --- | --- | --- | --- | --- | --- | --- |
| `tasks.resultWait` | duration | `2m0s` | call | yes | `--tasks-result-wait` | `MCPX_TASKS_RESULT_WAIT` | how long collecting a task result blocks before giving up |
| `tasks.ttl` | duration | `10m0s` | daemon | yes | `--tasks-ttl` | `MCPX_TASKS_TTL` | how long a finished task's result is kept, measured from when the task finishes; a still-running task is never expired by it |
| `tasks.ttl` | duration | `10m0s` | daemon | yes | `--tasks-ttl` | `MCPX_TASKS_TTL` | how long a finished task's result is kept |

### transport

Expand Down
9 changes: 8 additions & 1 deletion pkgs/mcpx/internal/cli/commands.go
Original file line number Diff line number Diff line change
Expand Up @@ -1121,7 +1121,11 @@ func (a *App) runScript(ctx context.Context, args []string, inline bool) error {
if err != nil {
return err
}
env := runEnvelope(res, out.String(), collected, streamed)
// The envelope carries the service's capped stdout
// (res.Stdout), not the raw stream captured in out: the raw
// copy would hand back output the exec.maxOutputBytes cap
// already cut, with no truncation indication.
env := runEnvelope(res, res.Stdout, collected, streamed)
if s := errOut.String(); s != "" {
env["stderr"] = s
}
Expand Down Expand Up @@ -1191,6 +1195,9 @@ func runEnvelope(res *execsvc.Result, stdout string, logs []logging.Record, stre
if res.TimedOut {
env["timedOut"] = true
}
if res.StdoutTruncated {
env["stdoutTruncated"] = true
}
// A script whose stdout is JSON almost always means it as its result, so
// offer it parsed as well as raw rather than making every caller re-parse.
if trimmed := strings.TrimSpace(stdout); trimmed != "" {
Expand Down
1 change: 1 addition & 0 deletions pkgs/mcpx/internal/cli/exec.go
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,7 @@ func (a *App) localService(store *artifacts.Store, socket string) *execsvc.Servi
lim.InlineMaxBytes = set.Bytes("artifacts.inlineMaxBytes")
lim.ChunkBytes = set.Bytes("artifacts.chunkBytes")
lim.InterceptImages = set.Bool("artifacts.interceptImages")
lim.StdoutLimit = set.Bytes("exec.maxOutputBytes")
Comment thread
dezren39 marked this conversation as resolved.
Resolved
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
return &execsvc.Service{
Store: store,
// The script runs in this process's machine, and the daemon whose
Expand Down
41 changes: 41 additions & 0 deletions pkgs/mcpx/internal/daemon/exec_stdout_limit_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package daemon

import (
"io"
"log"
"net/http"
"net/http/httptest"
"testing"

"github.com/dezren39/mcpx/internal/settings"
)

// #1937 (CODE-16) Codex finding: exec.maxOutputBytes is call-scoped, but
// the daemon's handleExec built its service from cached startup
// settings, so a per-request --exec-max-output-bytes was silently
// ignored for remote executions. handleExec now applies
// s.callSettings(r).Bytes("exec.maxOutputBytes") to the service it runs;
// this pins the resolution that assignment relies on: the header value
// wins for the one request, and without a header the daemon's own
// (default) value stands.
func TestCallSettingsExecMaxOutputBytes(t *testing.T) {
sch, err := settings.New(settings.Registry())
if err != nil {
t.Fatal(err)
}
s := &Server{
set: settings.NewSet(sch),
logger: log.New(io.Discard, "", 0),
}

req := httptest.NewRequest(http.MethodPost, "/v1/exec", nil)
req.Header.Set(CallSettingsHeader, `{"exec.maxOutputBytes":"1024"}`)
if got := s.callSettings(req).Bytes("exec.maxOutputBytes"); got != 1024 {
t.Errorf("request-scoped exec.maxOutputBytes = %d, want 1024", got)
}

bare := httptest.NewRequest(http.MethodPost, "/v1/exec", nil)
if got := s.callSettings(bare).Bytes("exec.maxOutputBytes"); got != 64*1024 {
t.Errorf("default exec.maxOutputBytes = %d, want %d (64KiB)", got, 64*1024)
}
}
7 changes: 7 additions & 0 deletions pkgs/mcpx/internal/daemon/routes_exec.go
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,7 @@ func (s *Server) ExecService() *execsvc.Service {
lim.InlineMaxBytes = set.Bytes("artifacts.inlineMaxBytes")
lim.ChunkBytes = set.Bytes("artifacts.chunkBytes")
lim.InterceptImages = set.Bool("artifacts.interceptImages")
lim.StdoutLimit = set.Bytes("exec.maxOutputBytes")
Comment thread
dezren39 marked this conversation as resolved.
Resolved

svc := &execsvc.Service{
Calls: s.callRegistry(),
Expand Down Expand Up @@ -251,6 +252,12 @@ func (s *Server) handleExec(w http.ResponseWriter, r *http.Request) {
return
}
svc := s.ExecService()
// exec.maxOutputBytes is call-scoped (settings/exec.go), so a value the
// client sent for this one request (--exec-max-output-bytes, forwarded
// via X-Mcpx-Settings) must govern this execution. ExecService builds
// from the daemon's cached startup settings and cannot see it; apply
// the request-resolved value to the service this request runs through.
svc.Limits.StdoutLimit = s.callSettings(r).Bytes("exec.maxOutputBytes")

// A task is a handle now and the result later, which is the right shape
// for a script that takes minutes: holding a request open that long
Expand Down
6 changes: 6 additions & 0 deletions pkgs/mcpx/internal/defaults/defaults.go
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,7 @@ type Defaults struct {
Programs int `json:"programs"`
Entries int `json:"entries"`
StderrLimit int `json:"stderrLimit"`
StdoutLimit int `json:"stdoutLimit"`
Output string `json:"output"`
RemoteOutput string `json:"remoteOutput"`
Delivery string `json:"delivery"`
Expand Down Expand Up @@ -679,6 +680,11 @@ var (
// explain the failure. Unbounded, a script looping on stderr would be
// held in memory in full, by the daemon, on someone else's behalf.
ExecStderrLimit = builtin.Exec.StderrLimit
// ExecStdoutLimit bounds how much of a run's stdout the returned
// Result carries (CODE-16, #1937). The full output still exists in
// the run record/artifacts where one is kept; this bounds only what
// is handed back into a caller's context.
ExecStdoutLimit = builtin.Exec.StdoutLimit
// ExecWorkDirs bounds how many content-addressed client directories are
// kept. One per distinct catalogue; without a bound it grows forever.
ExecWorkDirs = builtin.Exec.WorkDirs
Expand Down
1 change: 1 addition & 0 deletions pkgs/mcpx/internal/defaults/defaults.json
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,7 @@
"programs": 64,
"entries": 8,
"stderrLimit": 65536,
"stdoutLimit": 65536,
"output": "text",
"remoteOutput": "structured",
"delivery": "reference"
Expand Down
120 changes: 108 additions & 12 deletions pkgs/mcpx/internal/execsvc/execsvc.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ import (
"strings"
"sync"
"time"
"unicode/utf8"

"github.com/dezren39/mcpx/internal/artifacts"
"github.com/dezren39/mcpx/internal/defaults"
Expand Down Expand Up @@ -356,17 +357,21 @@ type LogRecord struct {

// Result is the structured answer.
type Result struct {
RunID string `json:"runId"`
Result any `json:"result,omitempty"`
Emits []json.RawMessage `json:"emits"`
Logs []LogRecord `json:"logs"`
Stdout string `json:"stdout"`
Artifacts []Artifact `json:"artifacts"`
ExitCode int `json:"exitCode"`
DurationMs int64 `json:"durationMs"`
Runtime string `json:"runtime,omitempty"`
TimedOut bool `json:"timedOut,omitempty"`
Error string `json:"error,omitempty"`
RunID string `json:"runId"`
Result any `json:"result,omitempty"`
Emits []json.RawMessage `json:"emits"`
Logs []LogRecord `json:"logs"`
Stdout string `json:"stdout"`
// StdoutTruncated is set when Stdout was capped at
// Limits.StdoutLimit (exec.maxOutputBytes, CODE-16); the end of
// Stdout itself carries the marker naming the dropped byte count.
StdoutTruncated bool `json:"stdoutTruncated,omitempty"`
Artifacts []Artifact `json:"artifacts"`
ExitCode int `json:"exitCode"`
DurationMs int64 `json:"durationMs"`
Runtime string `json:"runtime,omitempty"`
TimedOut bool `json:"timedOut,omitempty"`
Error string `json:"error,omitempty"`
}

// Source supplies the generated client the script is run against.
Expand Down Expand Up @@ -401,6 +406,8 @@ type Limits struct {
InlineMaxBytes int64
ChunkBytes int64
InterceptImages bool
// StdoutLimit caps the stdout a Result returns (bytes); <= 0 is no cap.
StdoutLimit int64
}

// DefaultLimits are the built-in values, before any configuration.
Expand All @@ -414,6 +421,7 @@ func DefaultLimits() Limits {
InlineMaxBytes: defaults.ArtifactInlineMaxBytes,
ChunkBytes: defaults.ArtifactChunkBytes,
InterceptImages: defaults.ArtifactInterceptImages,
StdoutLimit: int64(defaults.ExecStdoutLimit),
}
}

Expand Down Expand Up @@ -798,11 +806,16 @@ func (s *Service) RunWith(ctx context.Context, ropts runner.Options, opts Option

// A script whose stdout is JSON almost always means it as its answer, so
// it is offered parsed as well as raw. The same rule `mcpx --json run`
// has always followed, kept identical so the two agree.
// has always followed, kept identical so the two agree. The parsed
// value is remembered so the truncation below can tell a
// stdout-derived Result from a hook replacement.
var stdoutParsed any
haveStdoutParsed := false
if trimmed := strings.TrimSpace(res.Stdout); trimmed != "" {
var parsed any
if json.Unmarshal([]byte(trimmed), &parsed) == nil {
res.Result = parsed
stdoutParsed, haveStdoutParsed = parsed, true
}
}

Expand Down Expand Up @@ -871,6 +884,30 @@ func (s *Service) RunWith(ctx context.Context, ropts runner.Options, opts Option
if deliveryOf(opts, s.Limits) == DeliveryStream {
s.streamBodies(res, opts, emitFrame)
}

// CODE-16 (#1937): the Result boundary is where returned stdout is
// capped, so every surface that returns a run -- CLI, /v1, MCP --
// sees the same capped stdout. Internal consumers above (the JSON
// answer parse, hooks) worked on the full text; only what is
// handed back is bounded. Full output is unchanged wherever a
// full record already exists.
if capped, truncated := truncateStdout(res.Stdout, s.Limits.StdoutLimit); truncated {
res.Stdout = capped
res.StdoutTruncated = true
Comment thread
dezren39 marked this conversation as resolved.
Resolved
// A Result that is still the stdout parse must not survive
// as a side channel around the cap: renderers (renderExec)
// treat a Result that no longer matches stdout as a hook
// replacement and re-present it in full. A hook replacement
// -- a value that differs from the stdout parse -- is the
// hook's own answer and is preserved.
if haveStdoutParsed && res.Result != nil {
if rb, err := json.Marshal(res.Result); err == nil {
if pb, err := json.Marshal(stdoutParsed); err == nil && string(rb) == string(pb) {
res.Result = nil
}
}
}
}
return res, sinkErr
}

Expand Down Expand Up @@ -1145,6 +1182,65 @@ func ArtifactsDirFor(cwd, dir string) string {
//
// The tail rather than the head: a stack trace ends with the line that
// matters, and a script that floods stderr floods it from the start.
// truncateStdout caps s at limit bytes, keeping the head and ending
// with a marker that names the dropped byte count, so truncation is
// visible, never silent. The returned string is at most limit bytes
// for EVERY positive limit, including one smaller than the marker
// itself (then the marker prefix alone fills the budget). A limit
// <= 0, or a string that already fits, is returned unchanged with
// truncated=false. The cut backs off to a UTF-8 rune boundary so it
// never splits a multi-byte rune.
func truncateStdout(s string, limit int64) (string, bool) {
if limit <= 0 || int64(len(s)) <= limit {
return s, false
}
marker := func(kept int) string {
return fmt.Sprintf("\n[mcpx: stdout truncated -- kept %d of %d bytes, dropped %d bytes; raise exec.maxOutputBytes to see more]", kept, len(s), len(s)-kept)
}
// The limit is a hard bound: when it cannot hold even the marker
// (kept = 0 is the shortest form), the marker's own prefix is the
// most informative thing that fits.
if int(limit) <= len(marker(0)) {
return marker(0)[:int(limit)], true
}
kept := int(limit) - len(marker(int(limit)))
// The marker's own length depends on kept's digit count; settle
// it. Each step is O(1): runeBoundary inspects only the last few
// bytes (see below), never the whole prefix.
for i := 0; i < 8; i++ {
kept = runeBoundary(s, kept)
want := int(limit) - len(marker(kept))
if want == kept {
break
Comment thread
dezren39 marked this conversation as resolved.
Resolved
}
kept = want
}
kept = runeBoundary(s, kept)
for kept > 0 && kept+len(marker(kept)) > int(limit) {
kept = runeBoundary(s, kept-1)
}
return s[:kept] + marker(kept), true
}

// runeBoundary returns kept, reduced by at most a few bytes so the
// cut does not split a multi-byte rune at the end of s[:kept]. It
// decodes only the last rune: an invalid byte EARLIER in s must not
// drag the cut back over the whole prefix (validating the shrinking
// prefix per dropped byte is quadratic on the arbitrary non-UTF-8
// bytes a subprocess can emit).
func runeBoundary(s string, kept int) int {
for i := 0; i < utf8.UTFMax && kept > 0; i++ {
if s[kept-1] < utf8.RuneSelf {
break // ASCII: the cut is already on a boundary
}
if _, size := utf8.DecodeLastRuneInString(s[:kept]); size > 1 {
break // the last rune is complete (or a real U+FFFD)
}
kept-- // split rune or stray byte: retreat one byte
}
return kept
}

type tailBuffer struct {
limit int
buf []byte
Expand Down
54 changes: 54 additions & 0 deletions pkgs/mcpx/internal/execsvc/stdout_limit_service_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package execsvc_test

import (
"strings"
"testing"

"github.com/dezren39/mcpx/internal/execsvc"
)

// CODE-16 (#1937), Codex P2 on PR 2979: when large JSON stdout is
// capped, the parsed Result must not survive as a side channel that
// lets a renderer re-present the uncapped answer in full.
func TestTruncatedJSONStdoutClearsStdoutDerivedResult(t *testing.T) {
svc := service(t, store(t))
svc.Limits.StdoutLimit = 200
res, _ := run(t, svc, `
import { installGlobals } from "./mcpx-client.ts";
installGlobals();
console.log(JSON.stringify({ data: "x".repeat(5000) }));
`, execsvc.Options{})

if !res.StdoutTruncated {
t.Fatal("expected StdoutTruncated")
}
if len(res.Stdout) > 200 {
t.Fatalf("capped stdout is %d bytes, over the 200-byte cap", len(res.Stdout))
}
if res.Result != nil {
t.Fatalf("stdout-derived Result survived truncation: %#v", res.Result)
}
}

// Under the cap the stdout-derived Result is offered parsed, as
// before: the clearing above must only fire on truncation.
func TestUntruncatedJSONStdoutKeepsResult(t *testing.T) {
svc := service(t, store(t))
svc.Limits.StdoutLimit = 200
res, _ := run(t, svc, `
import { installGlobals } from "./mcpx-client.ts";
installGlobals();
console.log(JSON.stringify({ total: 2 }));
`, execsvc.Options{})

if res.StdoutTruncated {
t.Fatal("under-cap output marked truncated")
}
m, ok := res.Result.(map[string]any)
if !ok || m["total"] != float64(2) {
t.Fatalf("JSON on stdout should be offered parsed, got %#v", res.Result)
}
if !strings.Contains(res.Stdout, "total") {
t.Fatalf("stdout = %q", res.Stdout)
}
}
Loading
Loading