GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — feat(relay): add tool discovery and routing table · majorcontext/keep@0ee3d3c

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • internal/relay
    • router.go
    • router_test.go
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎internal/relay/router.go‎

Copy file name to clipboard
+88Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
package relay
2+
3+
import (
4+
"context"
5+
"fmt"
6+
"log"
7+
8+
relayconfig "github.com/majorcontext/keep/internal/relay/config"
9+
"github.com/majorcontext/keep/internal/relay/mcp"
10+
)
11+
12+
// ToolRoute maps a tool to its upstream client and scope.
13+
type ToolRoute struct {
14+
Client *mcp.Client
15+
Scope string
16+
Tool mcp.Tool
17+
}
18+
19+
// Router maps tool names to upstream MCP clients and scopes.
20+
type Router struct {
21+
routes map[string]*ToolRoute // keyed by tool name
22+
tools []mcp.Tool // merged list of all tools
23+
}
24+
25+
// NewRouter connects to all configured upstreams, discovers tools,
26+
// and builds a routing table. Returns an error if any tool name
27+
// appears in multiple upstreams.
28+
func NewRouter(ctx context.Context, routes []relayconfig.Route) (*Router, error) {
29+
router := &Router{routes: make(map[string]*ToolRoute)}
30+
31+
for _, route := range routes {
32+
// Build client options from auth config
33+
var opts []mcp.ClientOption
34+
if route.Auth != nil {
35+
switch route.Auth.Type {
36+
case "bearer":
37+
opts = append(opts, mcp.WithBearerToken(route.Auth.TokenEnv))
38+
case "header":
39+
opts = append(opts, mcp.WithHeader(route.Auth.Header, route.Auth.TokenEnv))
40+
}
41+
}
42+
43+
client := mcp.NewClient(route.Upstream, opts...)
44+
45+
// Initialize
46+
_, err := client.Initialize(ctx)
47+
if err != nil {
48+
log.Printf("relay: upstream %q unreachable: %v (skipping)", route.Upstream, err)
49+
continue
50+
}
51+
52+
// Discover tools
53+
tools, err := client.ListTools(ctx)
54+
if err != nil {
55+
log.Printf("relay: upstream %q tool discovery failed: %v (skipping)", route.Upstream, err)
56+
continue
57+
}
58+
59+
// Register tools in routing table
60+
for _, tool := range tools {
61+
if existing, ok := router.routes[tool.Name]; ok {
62+
return nil, fmt.Errorf("relay: tool %q registered by both scope %q and scope %q", tool.Name, existing.Scope, route.Scope)
63+
}
64+
router.routes[tool.Name] = &ToolRoute{
65+
Client: client,
66+
Scope: route.Scope,
67+
Tool: tool,
68+
}
69+
router.tools = append(router.tools, tool)
70+
}
71+
}
72+
73+
return router, nil
74+
}
75+
76+
// Lookup returns the route for a tool name, or an error if not found.
77+
func (r *Router) Lookup(toolName string) (*ToolRoute, error) {
78+
route, ok := r.routes[toolName]
79+
if !ok {
80+
return nil, fmt.Errorf("relay: unknown tool %q", toolName)
81+
}
82+
return route, nil
83+
}
84+
85+
// Tools returns the merged list of all tools from all upstreams.
86+
func (r *Router) Tools() []mcp.Tool {
87+
return r.tools
88+
}
Collapse file

‎internal/relay/router_test.go‎

Copy file name to clipboard
+221Lines changed: 221 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,221 @@
1+
package relay
2+
3+
import (
4+
"context"
5+
"encoding/json"
6+
"net/http"
7+
"net/http/httptest"
8+
"strings"
9+
"testing"
10+
11+
relayconfig "github.com/majorcontext/keep/internal/relay/config"
12+
"github.com/majorcontext/keep/internal/relay/mcp"
13+
)
14+
15+
// mockUpstream starts a mock MCP server returning specific tools.
16+
func mockUpstream(t *testing.T, tools []mcp.Tool) *httptest.Server {
17+
t.Helper()
18+
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
19+
var req mcp.JSONRPCRequest
20+
json.NewDecoder(r.Body).Decode(&req)
21+
22+
var resp mcp.JSONRPCResponse
23+
resp.JSONRPC = "2.0"
24+
resp.ID = req.ID
25+
26+
switch req.Method {
27+
case "initialize":
28+
resp.Result = mcp.InitializeResult{
29+
ProtocolVersion: "2025-03-26",
30+
Capabilities: mcp.ServerCapabilities{Tools: &mcp.ToolsCapability{}},
31+
}
32+
case "tools/list":
33+
resp.Result = mcp.ListToolsResult{Tools: tools}
34+
case "tools/call":
35+
resp.Result = mcp.ToolCallResult{
36+
Content: []mcp.ContentBlock{{Type: "text", Text: "ok"}},
37+
}
38+
}
39+
40+
json.NewEncoder(w).Encode(resp)
41+
}))
42+
}
43+
44+
func TestRouter_BuildTable(t *testing.T) {
45+
toolA := mcp.Tool{Name: "tool_a", Description: "Tool A"}
46+
toolB := mcp.Tool{Name: "tool_b", Description: "Tool B"}
47+
48+
srv1 := mockUpstream(t, []mcp.Tool{toolA})
49+
defer srv1.Close()
50+
srv2 := mockUpstream(t, []mcp.Tool{toolB})
51+
defer srv2.Close()
52+
53+
routes := []relayconfig.Route{
54+
{Scope: "scope1", Upstream: srv1.URL},
55+
{Scope: "scope2", Upstream: srv2.URL},
56+
}
57+
58+
router, err := NewRouter(context.Background(), routes)
59+
if err != nil {
60+
t.Fatalf("NewRouter: unexpected error: %v", err)
61+
}
62+
63+
routeA, err := router.Lookup("tool_a")
64+
if err != nil {
65+
t.Fatalf("Lookup tool_a: %v", err)
66+
}
67+
if routeA.Scope != "scope1" {
68+
t.Errorf("tool_a scope: got %q, want %q", routeA.Scope, "scope1")
69+
}
70+
71+
routeB, err := router.Lookup("tool_b")
72+
if err != nil {
73+
t.Fatalf("Lookup tool_b: %v", err)
74+
}
75+
if routeB.Scope != "scope2" {
76+
t.Errorf("tool_b scope: got %q, want %q", routeB.Scope, "scope2")
77+
}
78+
}
79+
80+
func TestRouter_ToolConflict(t *testing.T) {
81+
conflictingTool := mcp.Tool{Name: "conflicting_tool", Description: "Conflict"}
82+
83+
srv1 := mockUpstream(t, []mcp.Tool{conflictingTool})
84+
defer srv1.Close()
85+
srv2 := mockUpstream(t, []mcp.Tool{conflictingTool})
86+
defer srv2.Close()
87+
88+
routes := []relayconfig.Route{
89+
{Scope: "scope1", Upstream: srv1.URL},
90+
{Scope: "scope2", Upstream: srv2.URL},
91+
}
92+
93+
_, err := NewRouter(context.Background(), routes)
94+
if err == nil {
95+
t.Fatal("NewRouter: expected error for conflicting tool, got nil")
96+
}
97+
if !strings.Contains(err.Error(), "conflicting_tool") {
98+
t.Errorf("error message does not mention tool name: %v", err)
99+
}
100+
}
101+
102+
func TestRouter_LookupHit(t *testing.T) {
103+
tool := mcp.Tool{Name: "my_tool", Description: "My Tool"}
104+
105+
srv := mockUpstream(t, []mcp.Tool{tool})
106+
defer srv.Close()
107+
108+
routes := []relayconfig.Route{
109+
{Scope: "myscope", Upstream: srv.URL},
110+
}
111+
112+
router, err := NewRouter(context.Background(), routes)
113+
if err != nil {
114+
t.Fatalf("NewRouter: %v", err)
115+
}
116+
117+
route, err := router.Lookup("my_tool")
118+
if err != nil {
119+
t.Fatalf("Lookup: %v", err)
120+
}
121+
122+
if route.Client == nil {
123+
t.Error("route.Client is nil")
124+
}
125+
if route.Scope != "myscope" {
126+
t.Errorf("route.Scope: got %q, want %q", route.Scope, "myscope")
127+
}
128+
if route.Tool.Name != "my_tool" {
129+
t.Errorf("route.Tool.Name: got %q, want %q", route.Tool.Name, "my_tool")
130+
}
131+
}
132+
133+
func TestRouter_LookupMiss(t *testing.T) {
134+
srv := mockUpstream(t, []mcp.Tool{{Name: "existing_tool"}})
135+
defer srv.Close()
136+
137+
routes := []relayconfig.Route{
138+
{Scope: "scope1", Upstream: srv.URL},
139+
}
140+
141+
router, err := NewRouter(context.Background(), routes)
142+
if err != nil {
143+
t.Fatalf("NewRouter: %v", err)
144+
}
145+
146+
_, err = router.Lookup("nonexistent_tool")
147+
if err == nil {
148+
t.Fatal("Lookup: expected error for unknown tool, got nil")
149+
}
150+
}
151+
152+
func TestRouter_MergedToolList(t *testing.T) {
153+
toolA := mcp.Tool{Name: "tool_a"}
154+
toolB := mcp.Tool{Name: "tool_b"}
155+
toolC := mcp.Tool{Name: "tool_c"}
156+
157+
srv1 := mockUpstream(t, []mcp.Tool{toolA, toolB})
158+
defer srv1.Close()
159+
srv2 := mockUpstream(t, []mcp.Tool{toolC})
160+
defer srv2.Close()
161+
162+
routes := []relayconfig.Route{
163+
{Scope: "scope1", Upstream: srv1.URL},
164+
{Scope: "scope2", Upstream: srv2.URL},
165+
}
166+
167+
router, err := NewRouter(context.Background(), routes)
168+
if err != nil {
169+
t.Fatalf("NewRouter: %v", err)
170+
}
171+
172+
tools := router.Tools()
173+
if len(tools) != 3 {
174+
t.Fatalf("Tools(): got %d tools, want 3", len(tools))
175+
}
176+
177+
names := make(map[string]bool)
178+
for _, tool := range tools {
179+
names[tool.Name] = true
180+
}
181+
for _, want := range []string{"tool_a", "tool_b", "tool_c"} {
182+
if !names[want] {
183+
t.Errorf("Tools() missing %q", want)
184+
}
185+
}
186+
}
187+
188+
func TestRouter_UpstreamDown(t *testing.T) {
189+
goodTool := mcp.Tool{Name: "good_tool"}
190+
191+
srvGood := mockUpstream(t, []mcp.Tool{goodTool})
192+
defer srvGood.Close()
193+
194+
// Use an invalid address that won't connect
195+
badUpstream := "http://127.0.0.1:1"
196+
197+
routes := []relayconfig.Route{
198+
{Scope: "bad", Upstream: badUpstream},
199+
{Scope: "good", Upstream: srvGood.URL},
200+
}
201+
202+
router, err := NewRouter(context.Background(), routes)
203+
if err != nil {
204+
t.Fatalf("NewRouter: expected success even with one down upstream, got: %v", err)
205+
}
206+
207+
// Bad upstream's tools should be excluded
208+
_, err = router.Lookup("bad_tool")
209+
if err == nil {
210+
t.Error("Lookup bad_tool: expected error, got nil")
211+
}
212+
213+
// Good upstream's tools should be available
214+
route, err := router.Lookup("good_tool")
215+
if err != nil {
216+
t.Fatalf("Lookup good_tool: %v", err)
217+
}
218+
if route.Scope != "good" {
219+
t.Errorf("good_tool scope: got %q, want %q", route.Scope, "good")
220+
}
221+
}

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.