From 5db367d407a794327b45d938cf564a184a4cec00 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Wed, 28 Oct 2026 18:17:11 -0500 Subject: [PATCH] mcpx(prompt): caller-supplied model/provider on the intent path; drop the sampling fallback from generate() (#1961) --- pkgs/mcpx/internal/cli/commands.go | 2 +- pkgs/mcpx/internal/cli/consumer.go | 41 +++-- pkgs/mcpx/internal/cli/intent_test.go | 53 +++++++ pkgs/mcpx/internal/daemon/consumer.go | 157 +++++++------------ pkgs/mcpx/internal/daemon/generate_test.go | 90 +++++++++++ pkgs/mcpx/internal/daemon/routes_consumer.go | 54 ++++--- 6 files changed, 265 insertions(+), 132 deletions(-) create mode 100644 pkgs/mcpx/internal/cli/intent_test.go create mode 100644 pkgs/mcpx/internal/daemon/generate_test.go diff --git a/pkgs/mcpx/internal/cli/commands.go b/pkgs/mcpx/internal/cli/commands.go index 8b431331f..75ab37389 100644 --- a/pkgs/mcpx/internal/cli/commands.go +++ b/pkgs/mcpx/internal/cli/commands.go @@ -663,7 +663,7 @@ func (a *App) runScript(ctx context.Context, args []string, inline bool) error { if sessionKey == "" { sessionKey = os.Getenv("MCPX_SESSION_ID") } - res, err := c.Intent(ctx, *promptFlag, "run", nil, sessionKey) + res, err := c.Intent(ctx, *promptFlag, "run", nil, sessionKey, "", "") if err != nil { return err } diff --git a/pkgs/mcpx/internal/cli/consumer.go b/pkgs/mcpx/internal/cli/consumer.go index 2a383fef9..a1a4e1acf 100644 --- a/pkgs/mcpx/internal/cli/consumer.go +++ b/pkgs/mcpx/internal/cli/consumer.go @@ -22,13 +22,13 @@ import ( // DiagnoseResult is what POST /v1/diagnose answers. type DiagnoseResult struct { - Valid bool `json:"valid"` - Diagnostics []diagnose.Diagnostic `json:"diagnostics"` - Fatal bool `json:"fatal"` + Valid bool `json:"valid"` + Diagnostics []diagnose.Diagnostic `json:"diagnostics"` + Fatal bool `json:"fatal"` Questions []scripting.ClarificationQuestion `json:"questions,omitempty"` - SuggestedFixes []string `json:"suggestedFixes,omitempty"` - Repaired string `json:"repaired,omitempty"` - RepairedValid bool `json:"repairedValid,omitempty"` + SuggestedFixes []string `json:"suggestedFixes,omitempty"` + Repaired string `json:"repaired,omitempty"` + RepairedValid bool `json:"repairedValid,omitempty"` } // Diagnose asks the daemon to explain a script. @@ -122,9 +122,18 @@ func (c *Client) RunRecipe(ctx context.Context, name string, values map[string]a map[string]any{"placeholders": values, "autonomy": autonomy, "session": session}) } -func (c *Client) Intent(ctx context.Context, prompt, autonomy string, values map[string]any, session string) (*Resolution, error) { - return c.resolution(ctx, "/v1/intent", - map[string]any{"prompt": prompt, "autonomy": autonomy, "placeholders": values, "session": session}) +// Intent asks the daemon to turn a prompt into a script (or its result). +// provider and model are the caller's own choice of generation model for +// this request; empty leaves the daemon's configured provider in place. +func (c *Client) Intent(ctx context.Context, prompt, autonomy string, values map[string]any, session, provider, model string) (*Resolution, error) { + body := map[string]any{"prompt": prompt, "autonomy": autonomy, "placeholders": values, "session": session} + if provider != "" { + body["provider"] = provider + } + if model != "" { + body["model"] = model + } + return c.resolution(ctx, "/v1/intent", body) } // resolution posts and reads the answer, refusal included. @@ -419,11 +428,13 @@ func parseAssignments(args []string) (map[string]any, error) { // CmdPrompt turns a request in words into a script, or runs it. func (a *App) CmdPrompt(ctx context.Context, args []string) error { - args = hoistFlags(args, map[string]bool{"autonomy": true, "session": true, "set": true}) + args = hoistFlags(args, map[string]bool{"autonomy": true, "session": true, "set": true, "provider": true, "model": true}) fs := newFlagSet("prompt") run := fs.Bool("run", false, "run the script instead of returning it, the same as --autonomy run") autonomy := fs.String("autonomy", "", "propose returns the script; run executes it (default: prompt.autonomy)") session := fs.String("session", "", "session key") + provider := fs.String("provider", "", "model provider to generate with, overriding the daemon's repair.provider for this request") + model := fs.String("model", "", "model to generate with, overriding the daemon's repair.model for this request") set := newRepeatable() fs.Var(set, "set", "placeholder value for a matched recipe, key=value; repeatable") if err := parseFlags(a, fs, args); err != nil { @@ -450,7 +461,7 @@ func (a *App) CmdPrompt(ctx context.Context, args []string) error { if err != nil { return err } - res, err := c.Intent(ctx, strings.Join(fs.Args(), " "), m, values, *session) + res, err := c.Intent(ctx, strings.Join(fs.Args(), " "), m, values, *session, *provider, *model) if err != nil { return err } @@ -469,7 +480,7 @@ func (a *App) showResolution(res *Resolution) error { return a.out(res) } // "No model is available" is information, not a failure: it is the - // default state of every caller that cannot answer sampling, and exiting + // default state of every caller with no provider configured, and exiting // non-zero for it would make the ordinary case look broken. if res.Source == "" && res.Model == "none" { fmt.Println(res.Message) @@ -486,7 +497,11 @@ func (a *App) showResolution(res *Resolution) error { if res.Recipe != "" { fmt.Fprintf(os.Stderr, "mcpx: recipe %s\n", res.Recipe) } else if res.Generated { - fmt.Fprintln(os.Stderr, "mcpx: generated by sampling; review it before running") + by := res.Model + if by == "" { + by = "a model" + } + fmt.Fprintf(os.Stderr, "mcpx: generated by %s; review it before running\n", by) } if len(res.Diagnostics) > 0 { fmt.Fprintln(os.Stderr, diagnose.Render(res.Diagnostics)) diff --git a/pkgs/mcpx/internal/cli/intent_test.go b/pkgs/mcpx/internal/cli/intent_test.go new file mode 100644 index 000000000..b6d0926c1 --- /dev/null +++ b/pkgs/mcpx/internal/cli/intent_test.go @@ -0,0 +1,53 @@ +package cli + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + + "github.com/dezren39/mcpx/internal/daemon" +) + +// #1961: Intent carries the caller's provider/model to /v1/intent when +// supplied, and omits them when not. +func TestIntentThreadsCallerProviderAndModel(t *testing.T) { + bodies := make(chan map[string]any, 2) + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/v1/intent" { + t.Errorf("path = %s", r.URL.Path) + } + var body map[string]any + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + t.Error(err) + } + bodies <- body + _, _ = w.Write([]byte(`{"autonomy":"propose","model":"provider:claude/opus","source":"return 1;"}`)) + })) + defer ts.Close() + + c := NewClientAt(daemon.Paths{}, "", ts.URL) + res, err := c.Intent(context.Background(), "do a thing", "propose", nil, "sess", "claude", "opus") + if err != nil { + t.Fatalf("Intent: %v", err) + } + if res.Model != "provider:claude/opus" { + t.Errorf("model = %q", res.Model) + } + body := <-bodies + if body["provider"] != "claude" || body["model"] != "opus" { + t.Errorf("body = %v, want provider/model threaded", body) + } + + if _, err := c.Intent(context.Background(), "do a thing", "propose", nil, "sess", "", ""); err != nil { + t.Fatalf("Intent: %v", err) + } + body = <-bodies + if _, ok := body["provider"]; ok { + t.Errorf("provider present in body when not supplied: %v", body) + } + if _, ok := body["model"]; ok { + t.Errorf("model present in body when not supplied: %v", body) + } +} diff --git a/pkgs/mcpx/internal/daemon/consumer.go b/pkgs/mcpx/internal/daemon/consumer.go index d3611208e..df16fe3e8 100644 --- a/pkgs/mcpx/internal/daemon/consumer.go +++ b/pkgs/mcpx/internal/daemon/consumer.go @@ -602,23 +602,25 @@ func prelude(nss []codegen.Namespace) string { return b.String() } -// ---- generation by sampling ---- +// ---- generation ---- -// generate asks whatever drives mcpx to write a script. +// generate asks a model provider to write a script. // -// mcpx has no model, which is the whole reason this goes through the broker: -// the request is a sampling request like any other, so every answerer that -// already exists -- the agent through `mcpx elicit`, the plugin through the -// opencode SDK, an MCP client that declared sampling -- answers it without -// learning anything new. +// mcpx has no model, so generation goes to a provider: the daemon's own +// repair.* configuration, or the provider/model the caller supplied on +// this intent request. It no longer falls back to an MCP sampling +// request: sampling is deprecated in MCP 2026-07-28, and the primary +// consumer cannot answer it (#1961). With no provider, generate returns +// errNoModel and the intent route answers with its no-model resolution. // -// What it is given is the part that needs care. The reason mcpx is worth -// having is that tool schemas stay out of a model's context, so a generation -// request sends the slice of the catalog the existing search ranked for this -// request, inside a budget, and nothing else. -func (s *Server) resolveProvider() scripting.Provider { +// What the provider is given is the part that needs care. The reason mcpx +// is worth having is that tool schemas stay out of a model's context, so +// a generation request sends the slice of the catalog the existing +// search ranked for this request, inside a budget, and nothing else. + +func (s *Server) providerConfig() scripting.ProviderConfig { if s.set == nil { - return scripting.ResolveProvider(scripting.ProviderConfig{}, nil) + return scripting.ProviderConfig{} } getString := func(key string) string { if v, ok := s.set.Value(key); ok { @@ -626,17 +628,42 @@ func (s *Server) resolveProvider() scripting.Provider { } return "" } - cfg := scripting.ProviderConfig{ + return scripting.ProviderConfig{ Type: getString("repair.provider"), BaseURL: getString("repair.url"), APIKey: getString("repair.apiKey"), Model: getString("repair.model"), Command: getString("repair.command"), } - return scripting.ResolveProvider(cfg, nil) } -func (s *Server) generate(ctx context.Context, prompt, session string) (string, string, error) { +func (s *Server) resolveProvider() scripting.Provider { + return scripting.ResolveProvider(s.providerConfig(), nil) +} + +// callerProviderConfig layers a caller-supplied provider and model (the +// intent request's provider/model fields, from `mcpx prompt --provider +// --model` or the /v1 caller) over the daemon's own configuration. An +// empty caller value leaves the daemon's setting in place. +func callerProviderConfig(base scripting.ProviderConfig, provider, model string) scripting.ProviderConfig { + if provider != "" { + base.Type = provider + } + if model != "" { + base.Model = model + } + return base +} + +// resolveProviderFor resolves the provider for one intent request: the +// caller's provider/model when supplied, the daemon's repair.* provider +// otherwise. +func (s *Server) resolveProviderFor(provider, model string) scripting.Provider { + return scripting.ResolveProvider( + callerProviderConfig(s.providerConfig(), provider, model), nil) +} + +func (s *Server) generate(ctx context.Context, prompt string, prov scripting.Provider, model string) (string, string, error) { nss, err := s.reg.CodegenNamespaces(nil, config.Profile{All: true}) if err != nil { return "", "", err @@ -651,93 +678,29 @@ func (s *Server) generate(ctx context.Context, prompt, session string) (string, "returning the result. Answer with the program only, no prose and no " + "code fences.\n\n" + slice - prov := s.resolveProvider() - if prov != nil { - text, perr := prov.Complete(ctx, scripting.CompletionRequest{ - SystemPrompt: system, - UserPrompt: prompt, - MaxTokens: s.policyFor(ctx).PromptMaxTokens, - Temperature: 0.2, - }) - if perr == nil && strings.TrimSpace(text) != "" { - return stripFences(text), "provider:" + prov.Name(), nil - } - } - - if s.reg.broker == nil { - return "", "", errNoSampler + if prov == nil { + return "", "", errNoModel } - - params, _ := json.Marshal(map[string]any{ - "messages": []any{map[string]any{ - "role": "user", - "content": map[string]any{"type": "text", "text": prompt}, - }}, - "systemPrompt": system, - "maxTokens": s.policyFor(ctx).PromptMaxTokens, + text, perr := prov.Complete(ctx, scripting.CompletionRequest{ + SystemPrompt: system, + UserPrompt: prompt, + MaxTokens: s.policyFor(ctx).PromptMaxTokens, + Temperature: 0.2, }) - - req := elicit.SampleAsk(elicit.Ask{ - Session: session, - Message: "mcpx is asking for a script: " + prompt, - TTL: s.policyFor(ctx).PromptSampleTimeout, - }, params) - - opened, oerr := s.reg.broker.OpenRequest(req) - if oerr != nil { - return "", "", oerr + if perr != nil || strings.TrimSpace(text) == "" { + return "", "", errNoModel } - s.reg.publish(events.Event{Kind: events.SampleOpened, Data: mustJSON(opened)}) - - actx, cancel := context.WithTimeout(ctx, s.policyFor(ctx).PromptSampleTimeout) - defer cancel() - ans, aerr := s.reg.broker.Await(actx, opened.ID) - if aerr != nil || ans.Action != elicit.Accept { - return "", opened.ID, errNoSampler + used := "provider:" + prov.Name() + if model != "" { + used += "/" + model } - text := sampledText(ans.Content) - if strings.TrimSpace(text) == "" { - return "", opened.ID, errNoSampler - } - return stripFences(text), opened.ID, nil + return stripFences(text), used, nil } -// errNoSampler means nothing answered the sampling request. -var errNoSampler = fmt.Errorf("no sampling answerer") - -// sampledText pulls the completion out of a CreateMessageResult. -func sampledText(raw json.RawMessage) string { - var doc struct { - Content json.RawMessage `json:"content"` - } - if json.Unmarshal(raw, &doc) != nil { - return "" - } - // Content is one block in the specification, but answerers write a list - // often enough that accepting both costs one branch and saves a support - // question. - var one struct { - Type string `json:"type"` - Text string `json:"text"` - } - if json.Unmarshal(doc.Content, &one) == nil && one.Text != "" { - return one.Text - } - var many []struct { - Type string `json:"type"` - Text string `json:"text"` - } - if json.Unmarshal(doc.Content, &many) == nil { - var parts []string - for _, b := range many { - if b.Text != "" { - parts = append(parts, b.Text) - } - } - return strings.Join(parts, "\n") - } - return "" -} +// errNoModel means no provider answered: mcpx has no model of its own, +// and generation no longer falls back to an MCP sampling request +// (sampling is deprecated in MCP 2026-07-28; #1961). +var errNoModel = fmt.Errorf("no model provider answered") // stripFences removes a markdown code fence a model wrapped the answer in. // diff --git a/pkgs/mcpx/internal/daemon/generate_test.go b/pkgs/mcpx/internal/daemon/generate_test.go new file mode 100644 index 000000000..2c504fc14 --- /dev/null +++ b/pkgs/mcpx/internal/daemon/generate_test.go @@ -0,0 +1,90 @@ +package daemon + +import ( + "context" + "errors" + "strings" + "testing" + + "github.com/dezren39/mcpx/internal/scripting" +) + +// #1961: a caller-supplied provider/model layers over the daemon's own +// repair.* configuration; empty caller values leave it untouched. +func TestCallerProviderConfig(t *testing.T) { + base := scripting.ProviderConfig{Type: "claude", Model: "daemon-model", BaseURL: "http://localhost:1"} + + got := callerProviderConfig(base, "opencode", "caller-model") + if got.Type != "opencode" || got.Model != "caller-model" { + t.Errorf("override = %+v, want type/model replaced", got) + } + if got.BaseURL != base.BaseURL { + t.Errorf("base URL changed: %+v", got) + } + + got = callerProviderConfig(base, "", "") + if got != base { + t.Errorf("empty override = %+v, want base %+v", got, base) + } +} + +func intentTestServer() *Server { + reg := &Registry{ + testTools: []ToolInfo{ + { + Namespace: "weather", + Tool: "forecast", + Function: "weather.forecast", + Description: "Get weather forecast for a city", + InputSchema: []byte(`{"type":"object","required":["city"],"properties":{"city":{"type":"string"}}}`), + }, + }, + } + return &Server{reg: reg} +} + +func intentCtx() context.Context { + return withPolicy(context.Background(), defaultConsumerPolicy()) +} + +// #1961: with no provider, generate returns errNoModel. It must not fall +// back to an MCP sampling request (the registry here has no broker at +// all, and the old code path would have opened one on it). +func TestGenerateNoProvider(t *testing.T) { + s := intentTestServer() + _, _, err := s.generate(intentCtx(), "get chicago weather", nil, "") + if !errors.Is(err, errNoModel) { + t.Fatalf("err = %v, want errNoModel", err) + } +} + +func TestGenerateProviderAnswers(t *testing.T) { + s := intentTestServer() + prov := scripting.NewCallbackProvider("mock-ai", func(ctx context.Context, req scripting.CompletionRequest) (string, error) { + if !strings.Contains(req.UserPrompt, "chicago") { + t.Errorf("user prompt = %q", req.UserPrompt) + } + return "const data = await tools.weather.forecast({city: 'Chicago'});\nreturn data;", nil + }) + source, used, err := s.generate(intentCtx(), "get chicago weather", prov, "mock-model") + if err != nil { + t.Fatalf("generate: %v", err) + } + if !strings.Contains(source, "tools.weather.forecast") { + t.Errorf("source = %q", source) + } + if used != "provider:mock-ai/mock-model" { + t.Errorf("used = %q, want provider:mock-ai/mock-model", used) + } +} + +func TestGenerateProviderFailureIsNoModel(t *testing.T) { + s := intentTestServer() + prov := scripting.NewCallbackProvider("down", func(ctx context.Context, req scripting.CompletionRequest) (string, error) { + return "", errors.New("connection refused") + }) + _, _, err := s.generate(intentCtx(), "get chicago weather", prov, "") + if !errors.Is(err, errNoModel) { + t.Fatalf("err = %v, want errNoModel", err) + } +} diff --git a/pkgs/mcpx/internal/daemon/routes_consumer.go b/pkgs/mcpx/internal/daemon/routes_consumer.go index 697252709..0198957cc 100644 --- a/pkgs/mcpx/internal/daemon/routes_consumer.go +++ b/pkgs/mcpx/internal/daemon/routes_consumer.go @@ -363,6 +363,8 @@ func (s *Server) handleIntent(w http.ResponseWriter, r *http.Request) { Autonomy string `json:"autonomy"` Placeholders map[string]any `json:"placeholders"` Session string `json:"session"` + Provider string `json:"provider"` + Model string `json:"model"` } if err := json.NewDecoder(r.Body).Decode(&req); err != nil { writeErr(w, http.StatusBadRequest, err) @@ -399,46 +401,56 @@ func (s *Server) handleIntent(w http.ResponseWriter, r *http.Request) { out.setLevel(level) if !settings.AutonomyAtLeast(level.Value, "propose") { // Generating a script nobody may see would spend a model's time on - // nothing, so below propose there is no sampling request at all. + // nothing, so below propose there is no generation at all. out.Model = "none" out.Message = belowPropose(level.Value) writeJSON(w, 200, out) return } - prov := s.resolveProvider() + prov := s.resolveProviderFor(req.Provider, req.Model) + // The model actually used, for the Resolution: the caller's model + // when supplied, the daemon's configured one otherwise. + model := req.Model + if model == "" { + model = s.providerConfig().Model + } // prompt.sample is whether mcpx may ask a model at all. A CLI found on // this machine is not permission to ask one, so only "ask" lifts the - // default; without it a host with opencode installed paid the full - // sampling deadline on every unmatched prompt. - if pol.PromptSample != "ask" || (s.reg.broker == nil && prov == nil) { + // default; without it a host with opencode installed paid for a model + // call on every unmatched prompt. A caller naming a provider or model + // on this request has asked, for this request. + asked := pol.PromptSample == "ask" || req.Provider != "" || req.Model != "" + if !asked || prov == nil { out.Model = "none" - out.Message = "no recipe matched, and generating one is off " + - "(prompt.sample is " + pol.PromptSample + "). " + - "The ranked recipes above are everything mcpx can offer deterministically." + if !asked { + out.Message = "no recipe matched, and generating one is off " + + "(prompt.sample is " + pol.PromptSample + "). " + + "The ranked recipes above are everything mcpx can offer deterministically." + } else { + out.Message = "no recipe matched, and no model provider is " + + "available: mcpx has no model of its own, and neither the " + + "daemon's repair.provider settings nor this request's " + + "provider/model named a usable one. " + + "The ranked recipes above are everything mcpx can offer deterministically." + } writeJSON(w, 200, out) return } - source, id, err := s.generate(r.Context(), req.Prompt, req.Session) + source, used, err := s.generate(r.Context(), req.Prompt, prov, model) if err != nil { out.Model = "none" - out.Message = fmt.Sprintf( - "no recipe matched, and no model answered the sampling request within %s "+ - "(elicitation %s). mcpx has no model of its own: generation needs "+ - "whatever drives it -- the agent, the opencode plugin, or an MCP "+ - "client that declared sampling -- to answer. The ranked recipes "+ - "above are everything mcpx can offer without one.", - pol.PromptSampleTimeout, id) + out.Message = "no recipe matched, and no model answered. " + + "mcpx has no model of its own: generation needs a provider " + + "-- the daemon's repair.provider/repair.model settings, or " + + "this request's provider/model -- to answer. The ranked " + + "recipes above are everything mcpx can offer without one." writeJSON(w, 200, out) return } out.Generated = true - if strings.HasPrefix(id, "provider:") { - out.Model = id - } else { - out.Model = "sampling" - } + out.Model = used out.Source = source cat := s.reg.DiagnoseCatalog() val := scripting.Validate(source, &cat)