StartHTTP runs the MCP server over HTTP (Streamable HTTP / SSE). This enables remote MCP access for AI assistants over the network. If authToken is non-empty, requests must include "Authorization: Bearer ".
(ctx context.Context, addr, authToken string, server *sdkmcp.Server)
| 12 | // This enables remote MCP access for AI assistants over the network. |
| 13 | // If authToken is non-empty, requests must include "Authorization: Bearer <token>". |
| 14 | func StartHTTP(ctx context.Context, addr, authToken string, server *sdkmcp.Server) error { |
| 15 | handler := sdkmcp.NewStreamableHTTPHandler( |
| 16 | func(r *http.Request) *sdkmcp.Server { |
| 17 | return server |
| 18 | }, |
| 19 | nil, |
| 20 | ) |
| 21 | |
| 22 | var h http.Handler = handler |
| 23 | if authToken != "" { |
| 24 | h = authMiddleware(authToken, handler) |
| 25 | } |
| 26 | |
| 27 | mux := http.NewServeMux() |
| 28 | mux.Handle("/", h) |
| 29 | |
| 30 | srv := &http.Server{Addr: addr, Handler: mux} |
| 31 | |
| 32 | slog.Info("MCP HTTP server started", "addr", addr, "auth", authToken != "") |
| 33 | |
| 34 | go func() { |
| 35 | <-ctx.Done() |
| 36 | srv.Shutdown(context.Background()) |
| 37 | }() |
| 38 | |
| 39 | if err := srv.ListenAndServe(); err != http.ErrServerClosed { |
| 40 | return err |
| 41 | } |
| 42 | return nil |
| 43 | } |
| 44 | |
| 45 | func authMiddleware(token string, next http.Handler) http.Handler { |
| 46 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
nothing calls this directly
no test coverage detected