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
2 changes: 1 addition & 1 deletion pkgs/mcpx/internal/cli/commands.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
41 changes: 28 additions & 13 deletions pkgs/mcpx/internal/cli/consumer.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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 {
Expand All @@ -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
}
Expand All @@ -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)
Expand All @@ -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))
Expand Down
53 changes: 53 additions & 0 deletions pkgs/mcpx/internal/cli/intent_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
157 changes: 60 additions & 97 deletions pkgs/mcpx/internal/daemon/consumer.go
Original file line number Diff line number Diff line change
Expand Up @@ -602,41 +602,68 @@ 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 {
return v.Raw
}
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
Expand All @@ -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.
//
Expand Down
Loading
Loading