173 lines
5.6 KiB
Go
173 lines
5.6 KiB
Go
package chattools
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"io"
|
|
"net"
|
|
"net/http"
|
|
"slices"
|
|
)
|
|
|
|
// MaxRequestBytes bounds one MCP request body: a full show_html document plus
|
|
// JSON escaping and the envelope.
|
|
const MaxRequestBytes = 4 << 20
|
|
|
|
// LatestProtocolVersion is the MCP revision this server implements. Older
|
|
// revisions a client asks for are accepted: the subset used here (initialize,
|
|
// tools/list, tools/call, ping over streamable HTTP with JSON responses) is the
|
|
// same in each.
|
|
const LatestProtocolVersion = "2025-06-18"
|
|
|
|
var protocolVersions = []string{"2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"}
|
|
|
|
// Result is one tool call's outcome: short text for the model.
|
|
type Result struct {
|
|
Text string
|
|
IsError bool
|
|
}
|
|
|
|
// Service executes tool calls for the chat an endpoint token serves.
|
|
type Service interface {
|
|
// Known reports whether token is an issued endpoint token.
|
|
Known(ctx context.Context, token string) bool
|
|
// Call runs one tool. arguments is the raw JSON object the model sent.
|
|
Call(ctx context.Context, token, tool string, arguments json.RawMessage) Result
|
|
}
|
|
|
|
// Handler serves the MCP streamable HTTP transport for one endpoint token.
|
|
type Handler struct {
|
|
Service Service
|
|
Version string
|
|
}
|
|
|
|
type rpcRequest struct {
|
|
JSONRPC string `json:"jsonrpc"`
|
|
ID json.RawMessage `json:"id,omitempty"`
|
|
Method string `json:"method"`
|
|
Params json.RawMessage `json:"params,omitempty"`
|
|
}
|
|
|
|
type rpcError struct {
|
|
Code int `json:"code"`
|
|
Message string `json:"message"`
|
|
}
|
|
|
|
type rpcResponse struct {
|
|
JSONRPC string `json:"jsonrpc"`
|
|
ID json.RawMessage `json:"id"`
|
|
Result any `json:"result,omitempty"`
|
|
Error *rpcError `json:"error,omitempty"`
|
|
}
|
|
|
|
// Loopback reports whether a request came over the loopback interface. The
|
|
// endpoint is for harness processes on this machine only.
|
|
func Loopback(r *http.Request) bool {
|
|
host, _, err := net.SplitHostPort(r.RemoteAddr)
|
|
if err != nil {
|
|
return false
|
|
}
|
|
ip := net.ParseIP(host)
|
|
return ip != nil && ip.IsLoopback()
|
|
}
|
|
|
|
// ServeHTTP answers one POSTed JSON-RPC message. A browser request (any Origin
|
|
// header) and a non-loopback peer are refused, an unknown token is 404, and
|
|
// GET (the optional server-to-client stream) is not offered.
|
|
func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request, token string) {
|
|
if r.Header.Get("Origin") != "" || !Loopback(r) {
|
|
http.Error(w, "forbidden", http.StatusForbidden)
|
|
return
|
|
}
|
|
if h.Service == nil || !h.Service.Known(r.Context(), token) {
|
|
http.NotFound(w, r)
|
|
return
|
|
}
|
|
if r.Method != http.MethodPost {
|
|
w.Header().Set("Allow", http.MethodPost)
|
|
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
|
return
|
|
}
|
|
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, MaxRequestBytes))
|
|
if err != nil {
|
|
var tooLarge *http.MaxBytesError
|
|
if errors.As(err, &tooLarge) {
|
|
writeRPC(w, rpcResponse{JSONRPC: "2.0", ID: json.RawMessage("null"), Error: &rpcError{Code: -32600, Message: "request exceeds 4 MiB"}})
|
|
return
|
|
}
|
|
http.Error(w, "unreadable request", http.StatusBadRequest)
|
|
return
|
|
}
|
|
var request rpcRequest
|
|
if err := json.Unmarshal(body, &request); err != nil || request.JSONRPC != "2.0" || request.Method == "" {
|
|
writeRPC(w, rpcResponse{JSONRPC: "2.0", ID: json.RawMessage("null"), Error: &rpcError{Code: -32700, Message: "expected one JSON-RPC 2.0 request"}})
|
|
return
|
|
}
|
|
if len(request.ID) == 0 || string(request.ID) == "null" {
|
|
// A notification (notifications/initialized, cancellations) has no reply.
|
|
w.WriteHeader(http.StatusAccepted)
|
|
return
|
|
}
|
|
response := rpcResponse{JSONRPC: "2.0", ID: request.ID}
|
|
response.Result, response.Error = h.dispatch(r.Context(), token, request)
|
|
writeRPC(w, response)
|
|
}
|
|
|
|
func (h Handler) dispatch(ctx context.Context, token string, request rpcRequest) (any, *rpcError) {
|
|
switch request.Method {
|
|
case "initialize":
|
|
var params struct {
|
|
ProtocolVersion string `json:"protocolVersion"`
|
|
}
|
|
_ = json.Unmarshal(request.Params, ¶ms)
|
|
version := LatestProtocolVersion
|
|
if slices.Contains(protocolVersions, params.ProtocolVersion) {
|
|
version = params.ProtocolVersion
|
|
}
|
|
return map[string]any{
|
|
"protocolVersion": version,
|
|
"capabilities": map[string]any{"tools": map[string]any{"listChanged": false}},
|
|
"serverInfo": map[string]any{"name": ServerName, "title": "Pipelines", "version": h.version()},
|
|
"instructions": Instructions,
|
|
}, nil
|
|
case "ping":
|
|
return map[string]any{}, nil
|
|
case "tools/list":
|
|
return map[string]any{"tools": definitions()}, nil
|
|
case "tools/call":
|
|
var params struct {
|
|
Name string `json:"name"`
|
|
Arguments json.RawMessage `json:"arguments"`
|
|
}
|
|
if err := json.Unmarshal(request.Params, ¶ms); err != nil || params.Name == "" {
|
|
return nil, &rpcError{Code: -32602, Message: "tools/call needs a tool name"}
|
|
}
|
|
if !IsTool(params.Name) {
|
|
return nil, &rpcError{Code: -32602, Message: "unknown tool: " + params.Name}
|
|
}
|
|
if len(params.Arguments) == 0 || string(params.Arguments) == "null" {
|
|
params.Arguments = json.RawMessage("{}")
|
|
}
|
|
result := h.Service.Call(ctx, token, params.Name, params.Arguments)
|
|
return map[string]any{
|
|
"content": []map[string]any{{"type": "text", "text": result.Text}},
|
|
"isError": result.IsError,
|
|
}, nil
|
|
}
|
|
return nil, &rpcError{Code: -32601, Message: "method not found: " + request.Method}
|
|
}
|
|
|
|
func (h Handler) version() string {
|
|
if h.Version == "" {
|
|
return "dev"
|
|
}
|
|
return h.Version
|
|
}
|
|
|
|
func writeRPC(w http.ResponseWriter, response rpcResponse) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.Header().Set("Cache-Control", "no-store")
|
|
_ = json.NewEncoder(w).Encode(response)
|
|
}
|