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: 3 additions & 0 deletions pkgs/mcpx/docs/changes/proxy-timeout.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
sections: proxy
kind: Added
summary: configuration.md gains the proxy section (#2114): the new proxy.timeout setting (duration, 10m default, --proxy-timeout / MCPX_PROXY_TIMEOUT) that bounds how long the daemon waits for a chat-completions upstream, returning 502 when the deadline passes before response headers
Comment on lines +1 to +3

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Register the new history fragment in the compendium manifest

The new Markdown fragment has no entry in docs/compendium.manifest.json, so it introduces a failure in TestEveryDocumentHasAChapter. That test walks all module Markdown files, including docs/changes/, and reports any file absent from the manifest (internal/settings/compendium_test.go:123–166). Add an entry for this fragment, using the not-compendium role if appropriate for release-history fragments. This also follows the explicit documentation-registration requirement in internal/AGENTS.md.

AGENTS.md reference: pkgs/mcpx/internal/AGENTS.md:L17-L18

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 90bb132 (pushed to queue/3088-2114-proxy-timeout): added the docs/changes/proxy-timeout.md entry to pkgs/mcpx/docs/compendium.manifest.json with role not-compendium, matching the other docs/changes fragments. Verified on the laptop: TestEveryDocumentHasAChapter no longer lists proxy-timeout.md; its 4 remaining unregistered files (TESTING.md, docs/changes/docs-history-tool.md, docs/changes/protocol-capability-claims.md, docs/changes/research-and-findings-chapter.md) are identical on clean main — pre-existing, not introduced by this PR. Disposition by queue task 8803 (repo-worker-code, lane code-f).

7 changes: 7 additions & 0 deletions pkgs/mcpx/docs/compendium.manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -851,6 +851,13 @@
"lines": 3,
"note": "docs-history change fragment for #2499 (protoTasks.cancelGrace); history metadata consumed by the docs-history tooling, not a compendium page"
},
{
"path": "docs/changes/proxy-timeout.md",
"chapter": null,
"role": "not-compendium",
"lines": 3,
"note": "docs-history change fragment for #2114 (proxy.timeout); history metadata consumed by the docs-history tooling, not a compendium page"
},
{
"path": "docs/cli.md",
"chapter": "designs",
Expand Down
6 changes: 6 additions & 0 deletions pkgs/mcpx/docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -962,6 +962,12 @@ skipped launcher phases).
| `protoTasks.perMinute` | int | `120` | daemon | no | `--proto-tasks-per-minute` | `MCPX_PROTO_TASKS_PER_MINUTE` | the tasks/* admission window per requestor; 0 disables it |
| `protoTasks.pollInterval` | duration | `1s` | daemon | no | `--proto-tasks-poll-interval` | `MCPX_PROTO_TASKS_POLL_INTERVAL` | the pollInterval every task carries |

### proxy

| setting | kind | default | scope | hot | flag | variable | governs |
| --- | --- | --- | --- | --- | --- | --- | --- |
| `proxy.timeout` | duration | `10m` | daemon | no | `--proxy-timeout` | `MCPX_PROXY_TIMEOUT` | how long the daemon waits for a chat-completions upstream |

### recipes

| setting | kind | default | scope | hot | flag | variable | governs |
Expand Down
55 changes: 48 additions & 7 deletions pkgs/mcpx/internal/daemon/routes_proxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,43 @@ import (
"io"
"net/http"
"os"
"strconv"
"strings"
"time"

"github.com/developing-today/code/pkgs/mcpx/internal/defaults"
"github.com/developing-today/code/pkgs/mcpx/internal/logstore"
)

const proxyFeedbackCaptureLimit = 1 << 20

type cappedFeedbackBuffer struct {
buf bytes.Buffer
limit int
truncated bool
}

func (b *cappedFeedbackBuffer) Write(p []byte) (int, error) {
remaining := b.limit - b.buf.Len()
if remaining > 0 {
_, _ = b.buf.Write(p[:min(len(p), remaining)])
}
if len(p) > remaining {
b.truncated = true
}
// The buffer is a side channel for feedback only. Reporting the whole
// input as written keeps io.TeeReader from truncating the client stream.
return len(p), nil
}

func (b *cappedFeedbackBuffer) String() string {
output := b.buf.String()
if b.truncated {
output += fmt.Sprintf("\n[mcpx: feedback output truncated after %d bytes]", b.limit)
}
return output
}

type openAITool struct {
Type string `json:"type"`
Function openAIFunction `json:"function"`
Expand Down Expand Up @@ -60,8 +90,10 @@ func (s *Server) handleChatCompletions(w http.ResponseWriter, r *http.Request) {
// 2. Discover relevant tools semantically
maxTools := 5
if s.set != nil {
if m := s.set.Int("proxy.maxTools"); m > 0 {
maxTools = m
if value, ok := s.set.Value("proxy.maxTools"); ok {
if m, err := strconv.Atoi(value.Raw); err == nil && m > 0 {
maxTools = m
}
}
}

Expand Down Expand Up @@ -134,7 +166,9 @@ func (s *Server) handleChatCompletions(w http.ResponseWriter, r *http.Request) {
// 4. Determine upstream endpoint
upstreamURL := ""
if s.set != nil {
upstreamURL = s.set.String("proxy.upstreamUrl")
if value, ok := s.set.Value("proxy.upstreamUrl"); ok {
upstreamURL = value.Raw
}
}
if upstreamURL == "" {
upstreamURL = os.Getenv("OPENAI_BASE_URL")
Expand All @@ -145,7 +179,9 @@ func (s *Server) handleChatCompletions(w http.ResponseWriter, r *http.Request) {

apiKey := ""
if s.set != nil {
apiKey = s.set.String("proxy.apiKey")
if value, ok := s.set.Value("proxy.apiKey"); ok {
apiKey = value.Raw
}
}
if apiKey == "" {
apiKey = os.Getenv("OPENAI_API_KEY")
Expand Down Expand Up @@ -240,15 +276,20 @@ func (s *Server) proxyToUpstream(w http.ResponseWriter, r *http.Request, upstrea
upReq.Header.Set("Authorization", "Bearer "+apiKey)
}

resp, err := http.DefaultClient.Do(upReq)
upstreamTimeout := defaults.ProxyUpstreamTimeout
if s.set != nil {
upstreamTimeout = s.set.Duration("proxy.timeout")
}
client := &http.Client{Timeout: upstreamTimeout}
resp, err := client.Do(upReq)
if err != nil {
writeErr(w, http.StatusBadGateway, fmt.Errorf("upstream error: %w", err))
return
}
defer resp.Body.Close()

var buf bytes.Buffer
rdr := io.TeeReader(resp.Body, &buf)
buf := &cappedFeedbackBuffer{limit: proxyFeedbackCaptureLimit}
rdr := io.TeeReader(resp.Body, buf)

for k, vv := range resp.Header {
for _, v := range vv {
Expand Down
98 changes: 98 additions & 0 deletions pkgs/mcpx/internal/daemon/routes_proxy_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,13 @@ package daemon
import (
"bytes"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"path/filepath"
"strings"
"testing"
"time"

"github.com/developing-today/code/pkgs/mcpx/internal/logstore"
"github.com/developing-today/code/pkgs/mcpx/internal/settings"
Expand Down Expand Up @@ -197,3 +200,98 @@ func TestHandleChatCompletionsUpstreamProxy(t *testing.T) {
t.Errorf("expected chatcmpl-mock, got %v", resp["id"])
}
}

func TestProxyUpstreamTimeoutReturnsBadGateway(t *testing.T) {
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
select {
case <-r.Context().Done():
case <-time.After(time.Second):
w.WriteHeader(http.StatusOK)
}
}))
defer upstream.Close()

sch, err := settings.New(settings.Registry())
if err != nil {
t.Fatal(err)
}
set := settings.NewSet(sch).WithOverrides(map[string]string{
"proxy.timeout": "25ms",
}, "test")
s := &Server{reg: &Registry{}, set: set}

req := httptest.NewRequest(http.MethodPost, "/v1/chat/completions", strings.NewReader(`{"messages":[{"role":"user","content":"hello"}]}`))
req.Header.Set("X-Upstream-Url", upstream.URL)
w := httptest.NewRecorder()
started := time.Now()

s.handleChatCompletions(w, req)

if w.Code != http.StatusBadGateway {
t.Fatalf("status = %d, want 502; body: %s", w.Code, w.Body.String())
}
if elapsed := time.Since(started); elapsed >= 500*time.Millisecond {
t.Fatalf("timed-out upstream took %s, want under 500ms", elapsed)
}
}

func TestProxyCapsFeedbackCopyAndForwardsFullStream(t *testing.T) {
const captureLimit = 1 << 20
const chunk = "data: " + "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" + "\n\n"
var body strings.Builder
for body.Len() <= captureLimit {
body.WriteString(chunk)
}
upstreamBody := body.String()

upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
flusher, ok := w.(http.Flusher)
if !ok {
t.Error("upstream response writer does not support flushing")
return
}
for start := 0; start < len(upstreamBody); start += len(chunk) {
end := min(start+len(chunk), len(upstreamBody))
if _, err := io.WriteString(w, upstreamBody[start:end]); err != nil {
t.Errorf("write upstream chunk: %v", err)
return
}
flusher.Flush()
}
}))
defer upstream.Close()

fs, err := logstore.NewFeedbackStore(filepath.Join(t.TempDir(), "feedback.db"))
if err != nil {
t.Fatal(err)
}
defer fs.Close()
s := &Server{reg: &Registry{feedbackStore: fs}}

req := httptest.NewRequest(http.MethodPost, "/v1/chat/completions", strings.NewReader(`{"messages":[{"role":"user","content":"hello"}]}`))
req.Header.Set("X-Upstream-Url", upstream.URL)
w := httptest.NewRecorder()
s.handleChatCompletions(w, req)

if w.Code != http.StatusOK {
t.Fatalf("status = %d, want 200; body: %s", w.Code, w.Body.String())
}
if got := w.Body.String(); got != upstreamBody {
t.Fatalf("proxied body length = %d, want %d", len(got), len(upstreamBody))
}

rec, err := fs.Get(w.Header().Get("X-Mcpx-Trace-Id"))
if err != nil {
t.Fatal(err)
}
if len(rec.Output) > captureLimit+100 {
t.Fatalf("feedback output length = %d, exceeds capped size", len(rec.Output))
}
if !strings.HasPrefix(rec.Output, upstreamBody[:captureLimit]) {
t.Fatal("feedback output does not preserve the captured response prefix")
}
if !strings.Contains(rec.Output, "truncated after") {
t.Fatalf("feedback output lacks truncation marker: %q", rec.Output[len(rec.Output)-min(len(rec.Output), 100):])
}
}
4 changes: 4 additions & 0 deletions pkgs/mcpx/internal/defaults/defaults.go
Original file line number Diff line number Diff line change
Expand Up @@ -385,12 +385,16 @@ type Defaults struct {
RemoteTimeout string `json:"remoteTimeout"`
SearchTimeout string `json:"searchTimeout"`
} `json:"embeddings"`
Proxy struct {
Timeout string `json:"timeout"`
} `json:"proxy"`
}

// Embeddings defaults.
var (
EmbeddingsRemoteTimeout = mustDur(builtin.Embeddings.RemoteTimeout, "embeddings.remoteTimeout")
EmbeddingsSearchTimeout = mustDur(builtin.Embeddings.SearchTimeout, "embeddings.searchTimeout")
ProxyUpstreamTimeout = mustDur(builtin.Proxy.Timeout, "proxy.timeout")
)

// Upstream connection defaults.
Expand Down
3 changes: 3 additions & 0 deletions pkgs/mcpx/internal/defaults/defaults.json
Original file line number Diff line number Diff line change
Expand Up @@ -300,6 +300,9 @@
"remoteTimeout": "10s",
"searchTimeout": "2s"
},
"proxy": {
"timeout": "10m"
},
"hooks": {
"timeout": "2s"
}
Expand Down
2 changes: 2 additions & 0 deletions pkgs/mcpx/internal/e2e/effect_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ var implementedEffectProbes = map[string]string{
"deps.manifest": "TestDepsManifestNamesTheManifestResolutionReads",
"deps.packages": "TestDepsPackagesPinContradictingTheManifestFailsTheRun",
"paths.deps": "TestPathsDepsExtendsManifestDiscovery",
"proxy.timeout": "TestProxyUpstreamTimeoutIsReachableFromTheEnvironment",
}

// effectProbeFuncs anchors every declared probe name to the actual
Expand All @@ -65,6 +66,7 @@ var effectProbeFuncs = map[string]func(*testing.T){
"TestLoggingFileOffWritesNoDurableLog": TestLoggingFileOffWritesNoDurableLog,
"TestOutputJSONIsReachableFromTheEnvironment": TestOutputJSONIsReachableFromTheEnvironment,
"TestPathsConfigFileChangesWhichConfigLoads": TestPathsConfigFileChangesWhichConfigLoads,
"TestProxyUpstreamTimeoutIsReachableFromTheEnvironment": TestProxyUpstreamTimeoutIsReachableFromTheEnvironment,
"TestPoolDefaultsAreReachableFromTheEnvironment": TestPoolDefaultsAreReachableFromTheEnvironment,
"TestRegistryLimitReachesTheCLI": TestRegistryLimitReachesTheCLI,
"TestRegistryPageSizeChangesWhatTheCLIAsksFor": TestRegistryPageSizeChangesWhatTheCLIAsksFor,
Expand Down
52 changes: 52 additions & 0 deletions pkgs/mcpx/internal/e2e/proxy_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package e2e_test

import (
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)

func TestProxyUpstreamTimeoutIsReachableFromTheEnvironment(t *testing.T) {
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
select {
case <-r.Context().Done():
return
case <-time.After(200 * time.Millisecond):
}
w.Header().Set("Content-Type", "application/json")
_, _ = io.WriteString(w, `{"id":"chatcmpl-proxy-timeout-probe"}`)
}))
defer upstream.Close()

proxyStatus := func(t *testing.T, e *env) int {
t.Helper()
e.run("ls") // starts the isolated daemon with its final environment/config
client := e.socketClient(t)
req, err := http.NewRequest(http.MethodPost, "http://mcpx/v1/chat/completions",
strings.NewReader(`{"messages":[{"role":"user","content":"hello"}]}`))
if err != nil {
t.Fatal(err)
}
req.Header.Set("X-Upstream-Url", upstream.URL)
resp, err := client.Do(req)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
_, _ = io.Copy(io.Discard, resp.Body)
return resp.StatusCode
}

defaultEnv := newEnv(t, oneServer)
if got := proxyStatus(t, defaultEnv); got != http.StatusOK {
t.Fatalf("default timeout status = %d, want 200", got)
}

shortEnv := newEnv(t, oneServer).withEnv("MCPX_PROXY_TIMEOUT=25ms")
if got := proxyStatus(t, shortEnv); got != http.StatusBadGateway {
t.Fatalf("25ms proxy timeout status = %d, want 502", got)
}
}
1 change: 1 addition & 0 deletions pkgs/mcpx/internal/settings/effect.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ var EffectProbes = map[string]string{
"paths.deps": "TestPathsDepsExtendsManifestDiscovery",
"script.cwd": "TestScriptCwdIsReachableFromTheEnvironment",
"script.interpreter": "TestScriptInterpreterIsReachableFromTheEnvironment",
"proxy.timeout": "TestProxyUpstreamTimeoutIsReachableFromTheEnvironment",
}

// EffectExemptions maps a setting path to the reason no effect probe
Expand Down
20 changes: 20 additions & 0 deletions pkgs/mcpx/internal/settings/proxy.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package settings

import "github.com/developing-today/code/pkgs/mcpx/internal/defaults"

// proxySettings govern requests the daemon forwards to an LLM provider.
func proxySettings() []Setting {
return []Setting{
{
Path: "proxy.timeout", Scope: ScopeDaemon, Kind: KindDuration,
Default: defaults.Builtin().Proxy.Timeout,
Commands: []string{"daemon"},
Name: "Proxy upstream timeout",
Short: "how long the daemon waits for a chat-completions upstream",
Long: "The deadline covers the upstream response, including reading its body. " +
"A timeout before response headers arrive is returned to the caller as " +
"a 502. A stream that exceeds the deadline after headers have been sent " +
"is cut off, because an HTTP response status cannot be changed mid-stream.",
},
}
}
Loading
Loading