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
10 changes: 9 additions & 1 deletion pkgs/mcpx/internal/daemon/registry.go
Original file line number Diff line number Diff line change
Expand Up @@ -2102,7 +2102,15 @@ func (r *Registry) SearchSemanticOpts(query string, limit int, semantic bool, ta
// Combined hybrid score: 60% semantic cosine, 40% keyword
combined := float32(kwScore)*0.4 + (sim*100.0)*0.6
if fb := r.FeedbackStore(); fb != nil {
execMult, retrMult := fb.ToolFeedbackAdjustment(t.Function)
// Feedback recorded by the call path is keyed by the server
// identity, while ranking asks by this view's function name;
// pass the server identity as an alias so both spellings of
// the same tool share one feedback history.
alias := ""
if t.Server != "" {
alias = t.Server + "." + t.Tool
}
execMult, retrMult := fb.ToolFeedbackAdjustment(t.Function, alias)
combined = combined * retrMult * (0.5 + 0.5*execMult)
}
if combined > 15.0 || kwScore > 0 {
Expand Down
24 changes: 12 additions & 12 deletions pkgs/mcpx/internal/daemon/routes_proxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -242,12 +242,12 @@ func (s *Server) handleChatCompletions(w http.ResponseWriter, r *http.Request) {
if fb := s.reg.FeedbackStore(); fb != nil {
outStr := fmt.Sprintf("mcpx reverse proxy: semantically injected %d tools for query %q.", len(discovered), query)
_ = fb.RecordInteraction(logstore.InteractionRecord{
TraceID: turnID,
Timestamp: time.Now(),
Source: "proxy",
Input: query,
Output: outStr,
ToolsUsed: toolNames,
TraceID: turnID,
Timestamp: time.Now(),
Source: "proxy",
Input: query,
Output: outStr,
ToolsOffered: toolNames,
})
}

Expand Down Expand Up @@ -302,12 +302,12 @@ func (s *Server) proxyToUpstream(w http.ResponseWriter, r *http.Request, upstrea

if fb := s.reg.FeedbackStore(); fb != nil {
_ = fb.RecordInteraction(logstore.InteractionRecord{
TraceID: turnID,
Timestamp: time.Now(),
Source: "proxy",
Input: query,
Output: buf.String(),
ToolsUsed: toolNames,
TraceID: turnID,
Timestamp: time.Now(),
Source: "proxy",
Input: query,
Output: buf.String(),
ToolsOffered: toolNames,
})
}
}
Expand Down
171 changes: 142 additions & 29 deletions pkgs/mcpx/internal/logstore/feedback.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,17 @@ const (

// InteractionRecord represents an input/output turn or tool execution with its trace ID and feedback.
type InteractionRecord struct {
TraceID string `json:"traceId"`
Timestamp time.Time `json:"timestamp"`
SessionID string `json:"sessionId,omitempty"`
Source string `json:"source"` // "proxy", "call", "task", etc.
Input string `json:"input"`
Output string `json:"output,omitempty"`
ToolsUsed []string `json:"toolsUsed,omitempty"`
TraceID string `json:"traceId"`
Timestamp time.Time `json:"timestamp"`
SessionID string `json:"sessionId,omitempty"`
Source string `json:"source"` // "proxy", "call", "task", etc.
Input string `json:"input"`
Output string `json:"output,omitempty"`
ToolsUsed []string `json:"toolsUsed,omitempty"`
// ToolsOffered names the tools presented for selection (e.g. by the
// reverse proxy) that were not necessarily invoked. Retrieval feedback
// may speak for offered tools; execution feedback never does.
ToolsOffered []string `json:"toolsOffered,omitempty"`
Score *float64 `json:"score,omitempty"` // primary score (e.g. 1.0 = good, 0.0 = bad)
Target string `json:"target,omitempty"` // "retrieval" vs "execution"
RetrievalScore *float64 `json:"retrievalScore,omitempty"` // score for search / tool match relevance
Expand Down Expand Up @@ -103,15 +107,104 @@ func NewFeedbackStore(path string) (*FeedbackStore, error) {
_ = db.Close()
return nil, err
}
// Stores created before tools_offered existed gain the column in place;
// their rows keep NULL there, which reads back as "nothing offered".
if _, err := db.Exec(`ALTER TABLE interactions ADD COLUMN tools_offered TEXT`); err != nil &&
!strings.Contains(err.Error(), "duplicate column") {
_ = db.Close()
return nil, err
}
return &FeedbackStore{db: db}, nil
}

// canonicalToolIdentity returns the stable spelling of a tool identity: the
// namespace/function form ("browser.screenshot") that semantic ranking asks
// for. The historical direct-call spelling ("browser:screenshot") canonicalises
// to it; the separator is the first ':' or '.', and the remainder is the tool
// name verbatim. Identities without a separator are kept as-is.
func canonicalToolIdentity(raw string) string {
s := strings.TrimSpace(raw)
if i := strings.Index(s, ":"); i > 0 {
return s[:i] + "." + s[i+1:]
}
return s
}

// canonicalToolList canonicalises every identity in the list, dropping empty
// entries and duplicates while preserving order.
func canonicalToolList(in []string) []string {
var out []string
seen := make(map[string]bool, len(in))
for _, raw := range in {
id := canonicalToolIdentity(raw)
if id == "" || seen[id] {
continue
}
seen[id] = true
out = append(out, id)
}
return out
}

// toolIdentitySpellings returns every stored spelling equivalent to a tool
// identity: the canonical dot form and the historical colon form. Rows written
// before canonicalisation keep the colon spelling, so queries must accept both.
func toolIdentitySpellings(tool string) []string {
canon := canonicalToolIdentity(tool)
out := []string{canon}
if i := strings.Index(canon, "."); i > 0 {
if colon := canon[:i] + ":" + canon[i+1:]; colon != canon {
out = append(out, colon)
}
}
return out
}

// toolIdentitySet is the union of spellings for a tool and its aliases (e.g.
// the server identity behind a view's function name).
func toolIdentitySet(tool string, aliases []string) []string {
var out []string
seen := make(map[string]bool)
for _, t := range append([]string{tool}, aliases...) {
if strings.TrimSpace(t) == "" {
continue
}
for _, s := range toolIdentitySpellings(t) {
if !seen[s] {
seen[s] = true
out = append(out, s)
}
}
}
return out
}

// toolListMatch builds a SQL predicate (and its args) that matches a row when
// any of the given comma-joined list columns contains one of the identities as
// a whole element. instr() compares literally, so a tool never matches a
// longer name it is merely a prefix or substring of.
func toolListMatch(columns []string, identities []string) (string, []any) {
var preds []string
var args []any
for _, col := range columns {
for _, id := range identities {
preds = append(preds, "instr(',' || COALESCE("+col+", '') || ',', ',' || ? || ',') > 0")
args = append(args, id)
}
}
if len(preds) == 0 {
return "1 = 0", nil
}
return "(" + strings.Join(preds, " OR ") + ")", args
}

// RecordInteraction inserts or updates an interaction record.
func (fs *FeedbackStore) RecordInteraction(rec InteractionRecord) error {
fs.mu.Lock()
defer fs.mu.Unlock()

toolsStr := strings.Join(rec.ToolsUsed, ",")
toolsStr := strings.Join(canonicalToolList(rec.ToolsUsed), ",")
offeredStr := strings.Join(canonicalToolList(rec.ToolsOffered), ",")
tsMs := rec.Timestamp.UnixMilli()
if tsMs == 0 {
tsMs = time.Now().UnixMilli()
Expand All @@ -126,11 +219,12 @@ func (fs *FeedbackStore) RecordInteraction(rec InteractionRecord) error {
_, err := fs.db.Exec(`
INSERT INTO interactions (
trace_id, ts_unix_ms, session_id, source, input_text, output_text,
tools_used, score, target, retrieval_score, execution_score, scores_json, feedback_notes, feedback_ts_unix_ms
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
tools_used, tools_offered, score, target, retrieval_score, execution_score, scores_json, feedback_notes, feedback_ts_unix_ms
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(trace_id) DO UPDATE SET
output_text = COALESCE(excluded.output_text, interactions.output_text),
tools_used = CASE WHEN excluded.tools_used != '' THEN excluded.tools_used ELSE interactions.tools_used END,
tools_offered = CASE WHEN excluded.tools_offered != '' THEN excluded.tools_offered ELSE interactions.tools_offered END,
score = COALESCE(excluded.score, interactions.score),
target = COALESCE(excluded.target, interactions.target),
retrieval_score = COALESCE(excluded.retrieval_score, interactions.retrieval_score),
Expand All @@ -139,7 +233,7 @@ func (fs *FeedbackStore) RecordInteraction(rec InteractionRecord) error {
feedback_notes = COALESCE(excluded.feedback_notes, interactions.feedback_notes),
feedback_ts_unix_ms = COALESCE(excluded.feedback_ts_unix_ms, interactions.feedback_ts_unix_ms)
`, rec.TraceID, tsMs, rec.SessionID, rec.Source, rec.Input, rec.Output,
toolsStr, rec.Score, rec.Target, rec.RetrievalScore, rec.ExecutionScore, rec.ScoresJSON, rec.FeedbackNotes, fbMs)
toolsStr, offeredStr, rec.Score, rec.Target, rec.RetrievalScore, rec.ExecutionScore, rec.ScoresJSON, rec.FeedbackNotes, fbMs)
return err
}

Expand Down Expand Up @@ -209,20 +303,20 @@ func (fs *FeedbackStore) Get(traceID string) (*InteractionRecord, error) {

row := fs.db.QueryRow(`
SELECT trace_id, ts_unix_ms, session_id, source, input_text, output_text,
tools_used, score, target, retrieval_score, execution_score,
tools_used, tools_offered, score, target, retrieval_score, execution_score,
scores_json, feedback_notes, feedback_ts_unix_ms
FROM interactions WHERE trace_id = ?
`, traceID)

var rec InteractionRecord
var tsMs int64
var fbMs sql.NullInt64
var toolsStr sql.NullString
var toolsStr, offeredStr sql.NullString
var sessID, outText, tgt, sJSON, notes sql.NullString
var sc, rSc, eSc sql.NullFloat64

err := row.Scan(&rec.TraceID, &tsMs, &sessID, &rec.Source, &rec.Input, &outText,
&toolsStr, &sc, &tgt, &rSc, &eSc, &sJSON, &notes, &fbMs)
&toolsStr, &offeredStr, &sc, &tgt, &rSc, &eSc, &sJSON, &notes, &fbMs)
if err != nil {
return nil, err
}
Expand All @@ -237,6 +331,9 @@ func (fs *FeedbackStore) Get(traceID string) (*InteractionRecord, error) {
if toolsStr.Valid && toolsStr.String != "" {
rec.ToolsUsed = strings.Split(toolsStr.String, ",")
}
if offeredStr.Valid && offeredStr.String != "" {
rec.ToolsOffered = strings.Split(offeredStr.String, ",")
}
if sc.Valid {
v := sc.Float64
rec.Score = &v
Expand Down Expand Up @@ -340,7 +437,7 @@ func (fs *FeedbackStore) List(filter InteractionFilter) ([]InteractionRecord, er

query := fmt.Sprintf(`
SELECT trace_id, ts_unix_ms, session_id, source, input_text, output_text,
tools_used, score, target, retrieval_score, execution_score,
tools_used, tools_offered, score, target, retrieval_score, execution_score,
scores_json, feedback_notes, feedback_ts_unix_ms
FROM interactions
%s
Expand All @@ -359,12 +456,12 @@ func (fs *FeedbackStore) List(filter InteractionFilter) ([]InteractionRecord, er
var rec InteractionRecord
var tsMs int64
var fbMs sql.NullInt64
var toolsStr sql.NullString
var toolsStr, offeredStr sql.NullString
var sessID, outText, tgt, sJSON, notes sql.NullString
var sc, rSc, eSc sql.NullFloat64

if err := rows.Scan(&rec.TraceID, &tsMs, &sessID, &rec.Source, &rec.Input, &outText,
&toolsStr, &sc, &tgt, &rSc, &eSc, &sJSON, &notes, &fbMs); err == nil {
&toolsStr, &offeredStr, &sc, &tgt, &rSc, &eSc, &sJSON, &notes, &fbMs); err == nil {
rec.Timestamp = time.UnixMilli(tsMs)
if sessID.Valid {
rec.SessionID = sessID.String
Expand All @@ -375,6 +472,9 @@ func (fs *FeedbackStore) List(filter InteractionFilter) ([]InteractionRecord, er
if toolsStr.Valid && toolsStr.String != "" {
rec.ToolsUsed = strings.Split(toolsStr.String, ",")
}
if offeredStr.Valid && offeredStr.String != "" {
rec.ToolsOffered = strings.Split(offeredStr.String, ",")
}
if sc.Valid {
v := sc.Float64
rec.Score = &v
Expand Down Expand Up @@ -408,21 +508,30 @@ func (fs *FeedbackStore) List(filter InteractionFilter) ([]InteractionRecord, er

// ToolFeedbackAdjustment computes the feedback multipliers for tool execution and retrieval.
// Returns (executionMultiplier, retrievalMultiplier).
func (fs *FeedbackStore) ToolFeedbackAdjustment(tool string) (execMult float32, retrMult float32) {
//
// The tool is matched by exact identity: whole elements of the stored lists,
// under the canonical spelling, the historical colon spelling, and any alias
// the caller supplies (semantic ranking passes the server identity behind a
// view's function name). Execution evidence counts only interactions that
// actually invoked the tool; retrieval evidence also counts interactions that
// merely offered it, since retrieval feedback judges the offered set.
func (fs *FeedbackStore) ToolFeedbackAdjustment(tool string, aliases ...string) (execMult float32, retrMult float32) {
fs.mu.RLock()
defer fs.mu.RUnlock()

execMult = 1.0
retrMult = 1.0

likePattern := "%" + tool + "%"
identities := toolIdentitySet(tool, aliases)
invoked, invokedArgs := toolListMatch([]string{"tools_used"}, identities)
known, knownArgs := toolListMatch([]string{"tools_used", "tools_offered"}, identities)

// 1. Tool execution score: how reliably this tool executes
rowExec := fs.db.QueryRow(`
rowExec := fs.db.QueryRow(fmt.Sprintf(`
SELECT COUNT(*), AVG(COALESCE(execution_score, score))
FROM interactions
WHERE tools_used LIKE ? AND (execution_score IS NOT NULL OR target = 'execution' OR (target IS NULL AND score IS NOT NULL))
`, likePattern)
WHERE %s AND (execution_score IS NOT NULL OR target = 'execution' OR (target IS NULL AND score IS NOT NULL))
`, invoked), invokedArgs...)
var eCount int
var eAvg sql.NullFloat64
if err := rowExec.Scan(&eCount, &eAvg); err == nil && eCount > 0 && eAvg.Valid {
Expand All @@ -431,11 +540,11 @@ func (fs *FeedbackStore) ToolFeedbackAdjustment(tool string) (execMult float32,
}

// 2. Retrieval relevance score: how relevant this tool is when recommended for queries
rowRetr := fs.db.QueryRow(`
rowRetr := fs.db.QueryRow(fmt.Sprintf(`
SELECT COUNT(*), AVG(COALESCE(retrieval_score, score))
FROM interactions
WHERE tools_used LIKE ? AND (retrieval_score IS NOT NULL OR target = 'retrieval')
`, likePattern)
WHERE %s AND (retrieval_score IS NOT NULL OR target = 'retrieval')
`, known), knownArgs...)
var rCount int
var rAvg sql.NullFloat64
if err := rowRetr.Scan(&rCount, &rAvg); err == nil && rCount > 0 && rAvg.Valid {
Expand All @@ -447,20 +556,24 @@ func (fs *FeedbackStore) ToolFeedbackAdjustment(tool string) (execMult float32,
}

// FindCorrelatedQueries returns user queries that resulted in high retrieval feedback for a tool.
func (fs *FeedbackStore) FindCorrelatedQueries(tool string, minScore float64) []string {
// Matching is by exact tool identity (see ToolFeedbackAdjustment), and offered
// tools count: a query that scored well for a tool it was offered is evidence
// the tool belongs with that query.
func (fs *FeedbackStore) FindCorrelatedQueries(tool string, minScore float64, aliases ...string) []string {
fs.mu.RLock()
defer fs.mu.RUnlock()

likePattern := "%" + tool + "%"
known, knownArgs := toolListMatch([]string{"tools_used", "tools_offered"}, toolIdentitySet(tool, aliases))
args := append(append([]any{}, knownArgs...), minScore, minScore)
rows, err := fs.db.Query(fmt.Sprintf(`
SELECT input_text
FROM interactions
WHERE tools_used LIKE ?
WHERE %s
AND (retrieval_score >= ? OR (target = 'retrieval' AND score >= ?))
AND input_text != ''
ORDER BY ts_unix_ms DESC
LIMIT %d
`, defaults.RegistryLimit), likePattern, minScore, minScore)
`, known, defaults.RegistryLimit), args...)
if err != nil {
return nil
}
Expand Down
Loading