Implement variant-aware MCP server (#3)

Summary

Builds on the types and architecture from the previous PR to deliver a
working variant-aware MCP
server that routes requests to inner mcp.Server instances based on
per-request _meta variant selection,
enabling a single MCP endpoint to serve multiple tool/resource/prompt
variants simultaneously.
  
  ```go
 // Create standard mcp.Server instances — one per variant
codeReviewServer := mcp.NewServer(&mcp.Implementation{Name:
"devplatform", Version: "v1.0.0"}, nil)
mcp.AddTool(codeReviewServer, &mcp.Tool{Name: "list_pull_requests",
...}, handler)
mcp.AddTool(codeReviewServer, &mcp.Tool{Name: "get_diff", ...}, handler)

pmServer := mcp.NewServer(&mcp.Implementation{Name: "devplatform",
Version: "v1.0.0"}, nil)
  mcp.AddTool(pmServer, &mcp.Tool{Name: "list_issues", ...}, handler)
  mcp.AddTool(pmServer, &mcp.Tool{Name: "create_issue", ...}, handler)

  // Register them as variants on a single server
vs := variants.NewServer(&mcp.Implementation{Name: "devplatform",
Version: "v1.0.0"}).
      WithVariant(variants.ServerVariant{
          ID:          "code-review",
          Description: "PR and code review operations",
          Status:      variants.Stable,
      }, codeReviewServer, 0).
      WithVariant(variants.ServerVariant{
          ID:          "project-management",
          Description: "Issue and project tracking operations",
          Status:      variants.Stable,
      }, pmServer, 1)

      // Future: register variants backed by remote MCP servers
// WithHTTPVariant(v, mcpServer, priority) — variant backed by an
mcp.Server exposed over HTTP
// WithRemoteVariant(v, "https://...", priority) — variant backed by a
remote MCP endpoint

  // Serve over HTTP for multiple concurrent clients
  handler := variants.NewStreamableHTTPHandler(vs, nil)
  http.ListenAndServe(":8080", handler)

  // Or serve over stdio for single-client use:
  // vs.Run(ctx, &mcp.StdioTransport{})
```
  

  Key additions

  - Backend abstraction (inMemoryBackend) — creates in-memory transport pairs between the variant server and
   inner mcp.Server instances, with notification forwarding for progress and logging events.
  - Request dispatcher (dispatch.go) — handles routing for tools/list, tools/call, resources/list,
  resources/read, resources/subscribe, prompts/list, prompts/get, and completion/complete methods.
  Implements variant-scoped cursor wrapping to correctly paginate across multiple inner servers.
  - Session middleware (session.go) — manages per-session inner connections in stateful mode and shared
  connections in stateless HTTP mode, ensuring proper lifecycle management.
  - Initialize enrichment — injects availableVariants into the server's capabilities response so clients can
   discover which variants are available.
  - Capability discovery — merges inner server capabilities via union to present a unified capability set to
   clients.
  - NewStreamableHTTPHandler — provides an HTTP handler for multi-client serving over Streamable HTTP
  transport.
  - Integration tests (server_test.go, 458 lines) — covers end-to-end variant selection, backward
  compatibility (no variant specified), HTTP transport, and stateless modes.
  - Examples — stdio-based (examples/server/variants/main.go) and HTTP-based
  (examples/server/variants-http/main.go) example servers demonstrating the API.
  - README — rewritten with API documentation and architecture diagrams.


TODO (subsequent PRs):
- Unit Testing 
- More integration tests

Signed-off-by: Kurt Degiorgio <kdegiorgio@bloomberg.net>
This commit is contained in:
Kurt Degiorgio 2026-02-18 12:57:21 +00:00 • committed by GitHub
commit c01fd188d2
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -1,111 +1,108 @@
// Example: Setting up a variant-aware MCP server with multiple variants.
// Example: A developer productivity platform (à la GitHub) that exposes
// different tool sets for different agent types using MCP server variants.
//
// Variants:
// - code-review: PR operations, diffs, and review comments
// - project-management: issue tracking, labels, and assignments
// - security-readonly: security scanning alerts and advisories (read-only)
// - ci-automation: CI/CD workflow management and dispatch
//
// Run over stdio:
//
// go run .
package main
import (
"context"
"log"
mcp "github.com/modelcontextprotocol/go-sdk/mcp"
"github.com/modelcontextprotocol/go-sdk/mcp"
"github.com/modelcontextprotocol/experimental-ext-variants/go/sdk/examples/server/exampletools"
"github.com/modelcontextprotocol/experimental-ext-variants/go/sdk/variants"
)
// -- Coding variant tool types ------------------------------------------------
type AnalyzeCodeInput struct {
Code string `json:"code" jsonschema:"source code to analyze"`
Language string `json:"language" jsonschema:"programming language"`
}
type AnalyzeCodeOutput struct {
Issues []string `json:"issues"`
Suggestions []string `json:"suggestions"`
}
func AnalyzeCode(_ context.Context, _ *mcp.CallToolRequest, in AnalyzeCodeInput) (*mcp.CallToolResult, AnalyzeCodeOutput, error) {
return nil, AnalyzeCodeOutput{
Issues: []string{"unused variable on line 3"},
Suggestions: []string{"consider using a switch statement"},
}, nil
}
type RefactorInput struct {
Code string `json:"code" jsonschema:"source code to refactor"`
Action string `json:"action" jsonschema:"refactoring action, e.g. extract-function"`
}
type RefactorOutput struct {
Refactored string `json:"refactored"`
}
func Refactor(_ context.Context, _ *mcp.CallToolRequest, in RefactorInput) (*mcp.CallToolResult, RefactorOutput, error) {
return nil, RefactorOutput{Refactored: "// refactored\n" + in.Code}, nil
}
// -- Compact variant tool types -----------------------------------------------
type SummarizeInput struct {
Text string `json:"text" jsonschema:"text to summarize"`
}
type SummarizeOutput struct {
Summary string `json:"summary"`
}
func Summarize(_ context.Context, _ *mcp.CallToolRequest, in SummarizeInput) (*mcp.CallToolResult, SummarizeOutput, error) {
return nil, SummarizeOutput{Summary: in.Text[:min(len(in.Text), 50)]}, nil
}
type LookupInput struct {
Query string `json:"query" jsonschema:"lookup query"`
}
type LookupOutput struct {
Result string `json:"result"`
}
func Lookup(_ context.Context, _ *mcp.CallToolRequest, in LookupInput) (*mcp.CallToolResult, LookupOutput, error) {
return nil, LookupOutput{Result: "result for: " + in.Query}, nil
}
// -----------------------------------------------------------------------------
func main() {
// Server 1: coding-focused tools
server1 := mcp.NewServer(&mcp.Implementation{Name: "my-server", Version: "v1.0.0"}, nil)
mcp.AddTool(server1, &mcp.Tool{Name: "analyze_code", Description: "Perform static analysis on source code"}, AnalyzeCode)
mcp.AddTool(server1, &mcp.Tool{Name: "refactor", Description: "Apply a refactoring action to source code"}, Refactor)
// Code review variant: PR-focused tools for code review agents
codeReviewServer := mcp.NewServer(&mcp.Implementation{Name: "devplatform", Version: "v1.0.0"}, nil)
mcp.AddTool(codeReviewServer, &mcp.Tool{
Name: "list_pull_requests",
Description: "List open pull requests, optionally filtered by author",
}, exampletools.ListPullRequests)
mcp.AddTool(codeReviewServer, &mcp.Tool{
Name: "get_diff",
Description: "Get the diff for a pull request, including changed files and line counts",
}, exampletools.GetDiff)
mcp.AddTool(codeReviewServer, &mcp.Tool{
Name: "add_review_comment",
Description: "Post a review comment on a specific line of a pull request",
}, exampletools.AddReviewComment)
// Server 2: compact / minimal tools
server2 := mcp.NewServer(&mcp.Implementation{Name: "my-server", Version: "v1.0.0"}, nil)
mcp.AddTool(server2, &mcp.Tool{Name: "summarize", Description: "Summarize text"}, Summarize)
mcp.AddTool(server2, &mcp.Tool{Name: "lookup", Description: "Quick fact lookup"}, Lookup)
// Project management variant: issue-focused tools for PM agents
pmServer := mcp.NewServer(&mcp.Implementation{Name: "devplatform", Version: "v1.0.0"}, nil)
mcp.AddTool(pmServer, &mcp.Tool{
Name: "list_issues",
Description: "List issues, optionally filtered by state and labels",
}, exampletools.ListIssues)
mcp.AddTool(pmServer, &mcp.Tool{
Name: "create_issue",
Description: "Create a new issue with title, body, and optional labels",
}, exampletools.CreateIssue)
mcp.AddTool(pmServer, &mcp.Tool{
Name: "add_label",
Description: "Add labels to an existing issue",
}, exampletools.AddLabel)
coding := variants.ServerVariant{
ID: "coding-assistant",
Description: "Optimized for coding workflows",
Hints: map[string]string{"useCase": "coding", "contextSize": "standard"},
Status: variants.Stable,
}
// Security variant: read-only security scanning tools
securityServer := mcp.NewServer(&mcp.Implementation{Name: "devplatform", Version: "v1.0.0"}, nil)
mcp.AddTool(securityServer, &mcp.Tool{
Name: "list_security_alerts",
Description: "List code scanning alerts for a repository",
}, exampletools.ListSecurityAlerts)
mcp.AddTool(securityServer, &mcp.Tool{
Name: "get_advisory",
Description: "Get details of a security advisory",
}, exampletools.GetAdvisory)
compact := variants.ServerVariant{
ID: "compact",
Description: "Minimal token usage",
Hints: map[string]string{"contextSize": "small"},
Status: variants.Experimental,
}
// CI/CD variant: workflow management tools for automation agents
ciServer := mcp.NewServer(&mcp.Implementation{Name: "devplatform", Version: "v1.0.0"}, nil)
mcp.AddTool(ciServer, &mcp.Tool{
Name: "list_workflow_runs",
Description: "List recent workflow runs for a repository",
}, exampletools.ListWorkflowRuns)
mcp.AddTool(ciServer, &mcp.Tool{
Name: "trigger_workflow",
Description: "Trigger a workflow dispatch event",
}, exampletools.TriggerWorkflow)
vs := variants.NewServer().
WithVariant(coding, server1, 0).
WithVariant(compact, server2, 1).
WithRanking(func(_ context.Context, _ variants.VariantHints, vs []variants.ServerVariant) []variants.ServerVariant {
// rank based on client hints, return sorted
// note: this is optional, defults to ranking by priority.
return vs
})
vs := variants.NewServer(&mcp.Implementation{Name: "devplatform", Version: "v1.0.0"}).
WithVariant(variants.ServerVariant{
ID: "code-review",
Description: "Pull request and code review operations. Includes diff viewing, review comments, approval workflows, and merge controls.",
Hints: map[string]string{"domain": "code-review", "accessLevel": "read-write"},
Status: variants.Stable,
}, codeReviewServer, 0).
WithVariant(variants.ServerVariant{
ID: "project-management",
Description: "Issue and project tracking operations. Includes issue CRUD, labels, milestones, assignments, and project boards.",
Hints: map[string]string{"domain": "project-management", "accessLevel": "read-write"},
Status: variants.Stable,
}, pmServer, 1).
WithVariant(variants.ServerVariant{
ID: "security-readonly",
Description: "Security scanning and vulnerability management. Read-only access to code scanning alerts, secret detection, and security advisories.",
Hints: map[string]string{"domain": "security", "accessLevel": "readonly"},
Status: variants.Stable,
}, securityServer, 2).
WithVariant(variants.ServerVariant{
ID: "ci-automation",
Description: "CI/CD workflow management. Trigger runs, monitor jobs, manage deployments designed for automation agents.",
Hints: map[string]string{"domain": "ci-cd", "accessLevel": "automation"},
Status: variants.Stable,
}, ciServer, 3)
ctx := context.Background()
if err := vs.Run(ctx, nil); err != nil {
if err := vs.Run(ctx, &mcp.StdioTransport{}); err != nil {
log.Fatal(err)
}
}