48 lines
1.7 KiB
Go
48 lines
1.7 KiB
Go
package tasktools
|
|
|
|
import (
|
|
"context"
|
|
"crypto/subtle"
|
|
"encoding/json"
|
|
"net/http"
|
|
|
|
"github.com/modelcontextprotocol/go-sdk/mcp"
|
|
)
|
|
|
|
const (
|
|
Endpoint = "http://archie.tools/mcp"
|
|
Sentinel = "archie-task-tools-sentinel"
|
|
)
|
|
|
|
type Backend interface {
|
|
List(context.Context, string) ([]*mcp.Tool, error)
|
|
Call(context.Context, string, string, json.RawMessage) (*mcp.CallToolResult, error)
|
|
Close(context.Context, string) error
|
|
}
|
|
|
|
// ServeHTTP creates a fresh view so tool discovery never outlives permissions.
|
|
func ServeHTTP(ctx context.Context, w http.ResponseWriter, r *http.Request, backend Backend, credential, token string) {
|
|
if token == "" || subtle.ConstantTimeCompare([]byte(r.Header.Get("Authorization")), []byte("Bearer "+token)) != 1 {
|
|
http.Error(w, "invalid gateway credential", http.StatusUnauthorized)
|
|
return
|
|
}
|
|
tools, err := backend.List(ctx, credential)
|
|
if err != nil {
|
|
http.Error(w, "task tools unavailable", http.StatusBadGateway)
|
|
return
|
|
}
|
|
server := mcp.NewServer(&mcp.Implementation{Name: "archie-central", Version: "1"}, nil)
|
|
for _, tool := range tools {
|
|
server.AddTool(tool, func(methodCtx context.Context, req *mcp.CallToolRequest) (*mcp.CallToolResult, error) {
|
|
// MCP handler contexts may outlive HTTP; proxy revocation must not.
|
|
callCtx, cancel := context.WithCancel(methodCtx)
|
|
defer cancel()
|
|
stop := context.AfterFunc(ctx, cancel)
|
|
defer stop()
|
|
return backend.Call(callCtx, credential, req.Params.Name, req.Params.Arguments)
|
|
})
|
|
}
|
|
// The proxy has already authenticated the session and confined Host and path.
|
|
mcp.NewStreamableHTTPHandler(func(*http.Request) *mcp.Server { return server }, &mcp.StreamableHTTPOptions{Stateless: true, DisableLocalhostProtection: true}).ServeHTTP(w, r.WithContext(ctx))
|
|
}
|