-
Notifications
You must be signed in to change notification settings - Fork 3
feat: Expose the assistant tool set over an MCP server #186
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,78 @@ | ||
| package api | ||
|
|
||
| import ( | ||
| "context" | ||
| "encoding/json" | ||
| "net/http" | ||
|
|
||
| "github.com/flatrun/agent/internal/ai" | ||
| "github.com/flatrun/agent/internal/auth" | ||
| "github.com/flatrun/agent/internal/contextkeys" | ||
| "github.com/flatrun/agent/pkg/version" | ||
| "github.com/gin-gonic/gin" | ||
| "github.com/whilesmartgo/agents" | ||
| agentsmcp "github.com/whilesmartgo/mcp" | ||
| ) | ||
|
|
||
| // mcpActorKey carries the request's authenticated actor into the MCP handler's | ||
| // per-request registry callback, which only sees the raw *http.Request. | ||
| type mcpActorKey struct{} | ||
|
|
||
| // newMCPHandler builds the HTTP handler that serves the assistant tool set over | ||
| // MCP. The registry is resolved per request, so every call is authorized as the | ||
| // actor on that request rather than whoever opened the session. | ||
| func (s *Server) newMCPHandler() http.Handler { | ||
| return agentsmcp.StreamableHTTPHandler("flatrun", version.Get().Version, func(r *http.Request) *agents.Registry { | ||
| actor, _ := r.Context().Value(mcpActorKey{}).(*auth.ActorContext) | ||
| return s.mcpToolRegistry(actor) | ||
| }) | ||
| } | ||
|
|
||
| // mcpHTTP adapts the gin request to the MCP handler, passing the actor the auth | ||
| // middleware already resolved so tool handlers can gate on it. The route is | ||
| // always mounted; the flag is checked here so it can toggle at runtime. | ||
| func (s *Server) mcpHTTP(c *gin.Context) { | ||
| if !s.config.MCP.Enabled { | ||
| c.JSON(http.StatusServiceUnavailable, gin.H{"error": "the MCP server is disabled"}) | ||
| return | ||
| } | ||
| ctx := context.WithValue(c.Request.Context(), mcpActorKey{}, auth.GetActorFromContext(c)) | ||
| s.mcpHandler.ServeHTTP(c.Writer, c.Request.WithContext(ctx)) | ||
| } | ||
|
|
||
| // mcpToolRegistry wraps every assistant tool (built-in and plugin-contributed) | ||
| // as an agents.Tool bound to actor. Each handler runs through runAITool, the | ||
| // same dispatch the assistant uses, so authorization, protected-mode gating, | ||
| // plugin routing, and output truncation are identical. | ||
| func (s *Server) mcpToolRegistry(actor *auth.ActorContext) *agents.Registry { | ||
| specs := s.aiToolSpecs() | ||
| tools := make([]agents.Tool, 0, len(specs)) | ||
| for _, spec := range specs { | ||
| spec := spec | ||
| tools = append(tools, agents.Tool{ | ||
| Name: spec.Name, | ||
| Description: spec.Description, | ||
| Parameters: spec.Parameters, | ||
| Handler: func(ctx context.Context, raw json.RawMessage) (string, error) { | ||
| gc := toolGinContext(ctx, actor) | ||
| // runAITool returns tool errors as content (prefixed "Error: "), | ||
| // matching what the assistant sees, so an MCP client's model can | ||
| // read the failure and adapt rather than the call faulting. | ||
| return s.runAITool(gc, "", ai.ToolCall{Name: spec.Name, Arguments: string(raw)}), nil | ||
| }, | ||
| }) | ||
| } | ||
| return agents.NewRegistry(tools...) | ||
| } | ||
|
|
||
| // toolGinContext builds the minimal gin.Context the tool dispatch expects: a | ||
| // request carrying ctx (for per-tool timeouts) and the actor for permission | ||
| // checks. A nil actor means auth is disabled, as elsewhere in the API. | ||
| func toolGinContext(ctx context.Context, actor *auth.ActorContext) *gin.Context { | ||
| req, _ := http.NewRequestWithContext(ctx, http.MethodPost, "/", nil) | ||
| gc := &gin.Context{Request: req} | ||
| if actor != nil { | ||
| gc.Set(contextkeys.Actor, actor) | ||
| } | ||
| return gc | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,130 @@ | ||
| package api | ||
|
|
||
| import ( | ||
| "context" | ||
| "net/http" | ||
| "net/http/httptest" | ||
| "path/filepath" | ||
| "strings" | ||
| "testing" | ||
| "time" | ||
|
|
||
| "github.com/flatrun/agent/internal/ai" | ||
| "github.com/flatrun/agent/internal/auth" | ||
| "github.com/flatrun/agent/internal/docker" | ||
| "github.com/flatrun/agent/internal/files" | ||
| "github.com/flatrun/agent/internal/networks" | ||
| "github.com/flatrun/agent/internal/plan" | ||
| "github.com/flatrun/agent/internal/proxy" | ||
| "github.com/flatrun/agent/pkg/config" | ||
| "github.com/flatrun/agent/pkg/models" | ||
| "github.com/gin-gonic/gin" | ||
| "github.com/modelcontextprotocol/go-sdk/mcp" | ||
| ) | ||
|
|
||
| func setupMCPTestServer(t *testing.T) (*Server, string, *httptest.Server) { | ||
| t.Helper() | ||
| gin.SetMode(gin.TestMode) | ||
|
|
||
| tmpDir := t.TempDir() | ||
| cfg := &config.Config{ | ||
| DeploymentsPath: tmpDir, | ||
| Auth: config.AuthConfig{Enabled: false}, | ||
| Infrastructure: config.InfrastructureConfig{DefaultProxyNetwork: "proxy"}, | ||
| Nginx: config.NginxConfig{ConfigPath: filepath.Join(tmpDir, "nginx", "conf.d")}, | ||
| Cleanup: config.CleanupConfig{Timeout: 2 * time.Minute}, | ||
| Plans: config.PlansConfig{TTL: time.Hour, RetentionDays: 30}, | ||
| MCP: config.MCPConfig{Enabled: true}, | ||
| } | ||
|
|
||
| s := &Server{ | ||
| config: cfg, | ||
| router: gin.New(), | ||
| manager: docker.NewManager(tmpDir), | ||
| networksManager: networks.NewManager(), | ||
| authMiddleware: auth.NewMiddleware(&cfg.Auth), | ||
| proxyOrchestrator: proxy.NewOrchestrator(cfg), | ||
| planStore: plan.NewStore(tmpDir), | ||
| aiSessions: ai.NewSessionStore(tmpDir), | ||
| filesManager: files.NewManager(tmpDir), | ||
| } | ||
| s.mcpHandler = s.newMCPHandler() | ||
| s.setupRoutes() | ||
|
|
||
| ts := httptest.NewServer(s.router) | ||
| t.Cleanup(ts.Close) | ||
| return s, tmpDir, ts | ||
| } | ||
|
|
||
| // TestMCPServerExposesToolsOverHTTP drives the MCP server through the real HTTP | ||
| // boundary with a real MCP client, the way an external client reaches it. | ||
| func TestMCPServerExposesToolsOverHTTP(t *testing.T) { | ||
| _, _, ts := setupMCPTestServer(t) | ||
|
|
||
| ctx := context.Background() | ||
| client := mcp.NewClient(&mcp.Implementation{Name: "test", Version: "v0"}, nil) | ||
| cs, err := client.Connect(ctx, &mcp.StreamableClientTransport{Endpoint: ts.URL + "/api/mcp"}, nil) | ||
| if err != nil { | ||
| t.Fatalf("connect: %v", err) | ||
| } | ||
| t.Cleanup(func() { _ = cs.Close() }) | ||
|
|
||
| tools, err := cs.ListTools(ctx, nil) | ||
| if err != nil { | ||
| t.Fatalf("list tools: %v", err) | ||
| } | ||
| var found bool | ||
| for _, tool := range tools.Tools { | ||
| if tool.Name == "get_instance_info" { | ||
| found = true | ||
| } | ||
| } | ||
| if !found { | ||
| t.Fatal("expected a built-in assistant tool to be advertised over MCP") | ||
| } | ||
|
|
||
| res, err := cs.CallTool(ctx, &mcp.CallToolParams{Name: "get_instance_info"}) | ||
| if err != nil { | ||
| t.Fatalf("call tool: %v", err) | ||
| } | ||
| if text := res.Content[0].(*mcp.TextContent).Text; !strings.Contains(text, "Hostname:") { | ||
| t.Errorf("unexpected tool output %q", text) | ||
| } | ||
| } | ||
|
|
||
| // TestMCPServerRefusesWhenDisabled proves the route stays mounted but rejects | ||
| // calls once mcp.enabled flips off, so the toggle takes effect without a restart. | ||
| func TestMCPServerRefusesWhenDisabled(t *testing.T) { | ||
| s, _, ts := setupMCPTestServer(t) | ||
| s.config.MCP.Enabled = false | ||
|
|
||
| resp, err := http.Post(ts.URL+"/api/mcp", "application/json", strings.NewReader("{}")) | ||
| if err != nil { | ||
| t.Fatal(err) | ||
| } | ||
| defer func() { _ = resp.Body.Close() }() | ||
| if resp.StatusCode != http.StatusServiceUnavailable { | ||
| t.Errorf("disabled MCP endpoint status = %d, want 503", resp.StatusCode) | ||
| } | ||
| } | ||
|
|
||
| // TestMCPRegistryEnforcesActorPermissions proves the caller's actor flows | ||
| // through the bridge into the same per-tool gating the assistant uses: a viewer | ||
| // cannot drive a mutating tool. | ||
| func TestMCPRegistryEnforcesActorPermissions(t *testing.T) { | ||
| s, tmpDir, _ := setupMCPTestServer(t) | ||
| createTestDeployment(t, tmpDir, "myapp", &models.ServiceMetadata{Name: "myapp"}) | ||
|
|
||
| viewer := &auth.ActorContext{Role: auth.RoleViewer, User: &auth.User{ID: 1, Username: "v"}} | ||
| tool, ok := s.mcpToolRegistry(viewer).Get("control_deployment") | ||
| if !ok { | ||
| t.Fatal("control_deployment should be present") | ||
| } | ||
| out, err := tool.Handler(context.Background(), []byte(`{"deployment":"myapp","action":"restart"}`)) | ||
| if err != nil { | ||
| t.Fatalf("handler returned a transport error: %v", err) | ||
| } | ||
| if !strings.Contains(out, "write access") { | ||
| t.Errorf("a viewer must be denied a mutating tool, got %q", out) | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The manual construction of
gin.Contexthere leaves theWriterfield asnil. While current tool handlers might only read from the context, any future logic or middleware (such as a permission check that callsc.AbortWithStatusJSON) will trigger a nil pointer dereference panic when attempting to write to the response. Usinggin.CreateTestContextwith anhttptest.NewRecorderis a safer approach for internal dispatching. Note: This requires importingnet/http/httptest.