Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
108 changes: 106 additions & 2 deletions docs/mcp.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ Audit is on by default. To opt out:

### Request limits (`max_concurrent_requests` + `request_timeout`)

Both limits are off unless set; a value of zero or less disables that limit.
Defaults are 100 concurrent backend calls and a 30-second request timeout. Omitted settings retain these defaults, including when the `server` object contains other settings. Explicit `max_concurrent_requests: 0` or `request_timeout: "0s"` disables that limit; negative values also disable it.

```bash

Expand All @@ -79,6 +79,15 @@ Semantics:
- A call that the mode refuses, or that is waiting on a user's approval, holds no slot and spends none of its budget.
- Both outcomes are tool errors that name the setting and are written to the audit log. `server busy` means the call never ran, so it is safe to retry. A mutation or lifecycle call that timed out may already have taken effect at the provider, so check before retrying.
- Choose a `request_timeout` above the slowest call you expect; a call that exceeds it is cancelled.
- Cancellation is cooperative: backend work must honor its context. A permit remains held until that work exits, including cancellation cleanup, so timing out cannot bypass the concurrency cap.

### HTTP connection limits

The Streamable HTTP listener uses a 10-second header read timeout, a 30-second total request read timeout, a 60-second keep-alive idle timeout, and a 1 MiB maximum for request headers. MCP request bodies are limited to 4 MiB and larger requests receive HTTP 413. These transport limits are fixed and apply independently of the backend request limits above.

There is no HTTP write timeout. Streamable HTTP responses can remain open while delivering events, so a fixed write deadline could interrupt a valid long-lived response. The read timeout applies only while receiving a request, and the idle timeout applies between requests on a keep-alive connection.

The HTTP listener is registered for `Stop()`. Stopping the server or cancelling its `Start` context closes the listener and active connections; normal HTTP shutdown does not return a listener-closed error.

### Credential (re)sourcing (`--env.file` + `reload_credentials`)

Expand Down Expand Up @@ -219,7 +228,7 @@ Instructions, prompts, resources and tool descriptions are authored as markdown

## Server modes

`Config.Server.Mode` picks one of four safety contracts. All four allow SELECTs and metadata reads; they differ in how they handle mutations and lifecycle operations.
`Config.Server.Mode` picks one of four safety contracts. Metadata reads and classified read-only SELECTs are allowed; mutations, lifecycle operations and unresolved effects follow the mode gate.

| Mode | SELECT / metadata | INSERT / UPDATE / REPLACE / MERGE / UPSERT | DELETE | EXEC (lifecycle) |
|---|---|---|---|---|
Expand All @@ -228,6 +237,31 @@ Instructions, prompts, resources and tool descriptions are authored as markdown
| `delete_safe` | allow | allow | needs approval | needs approval |
| `full_access` | allow | allow | allow | allow |

**SQL classification limits (issue #818).** The MCP policy walks the parser AST,
including nested EXEC, subqueries and in-query CTE definitions. SELECTs over
`stackql_preview.iac.run`, `destroy` or `recover`, including abbreviated `iac.run`,
`iac.destroy` and `iac.recover`, are classified as lifecycle operations.
Recovery records operator attestations and updates local ledger state, even
though it does not call a cloud provider, so it is conservatively gated alongside
run and destroy. Bare relation names
outside an in-query CTE, other abbreviated names and unparseable SELECT/WITH
statements are unknown effects: `read_only` refuses them, `safe` and
`delete_safe` require approval, and `full_access` allows them. Use fully
qualified provider names for ordinary SELECTs. `run_select_query` retains its
existing refusal of known write/lifecycle classes in every mode; use a
mutation/lifecycle tool for approved effectful SQL.

This is not a complete semantic effect classifier or a closure of #818.
Fully qualified names can still resolve to persisted or provider-document views
whose definitions are unavailable to the MCP policy. Provider aliases, variable
substitution and document-defined or other effectful intrinsic relations also
require backend-owned resolution before effects can be proven safe. The backend
interface currently exposes execution and EXPLAIN-based validation, not an
effect-summary API. EXPLAIN output is not a substitute for that API. Do not rely
on `read_only` alone as a cloud-effect security boundary when these mechanisms
are available; restrict tools and provider credentials until semantic
classification is implemented in the parser/planner/backend.

**Refuse** returns an error immediately.

**Needs approval** uses the MCP elicitation flow, shaped by the negotiated protocol revision (see [Protocol revision support](#protocol-revision-support)):
Expand Down Expand Up @@ -288,6 +322,28 @@ Any other value fails config validation at startup (`invalid server.protocol_ver
- Streamable HTTP request bodies are capped at the SDK default of 4 MiB (`413` beyond it) and JSON nested deeper than 1000 levels is rejected before parsing; stackql's own stdio transport bounds a frame at 8 MiB (issue #701). None of these are configurable in `mcp.config`: they sit far above any SQL statement stackql accepts.
- Roots, sampling and server-side logging are deprecated by `2026-07-28` (SEP-2577). stackql uses none of them: it issues no roots or sampling requests and emits no `notifications/message`; the SDK's default `logging` capability stays advertised for the deprecation window.

### Feature and extension status

The root module and Go launcher use MCP Go SDK v1.8.0, released on
2026-09-14, with `2026-07-28` as the newest supported protocol revision.

| Feature | Status |
|---|---|
| Current and legacy protocol lifecycles, approval, structured results, and JSON schemas | Already supported. Existing tool names, arguments, and default rendering remain unchanged. |
| Response cache metadata | Added here. List responses have a private 30-second TTL; resource content and discovery are private and immediately stale. This does not cache query results. |
| OAuth Client Credentials, stable revision `2026-07-28` | The opt-in HTTP resource server validates signed JWTs issued by an external authorization server. It does not acquire tokens or implement an authorization server, so this alone is not full extension conformance. See [OAuth JWT resource-server authentication](#oauth-jwt-resource-server-authentication). |
| Enterprise-Managed Authorization | Not implemented. Centralized identity assertion and its trust model require separate design. |
| MCP Apps | Not implemented. The desktop bundle packages a server but does not implement the Apps UI protocol. |
| MCP Tasks, Skills over MCP, and Server Cards | Beta extensions are not enabled or advertised. Existing tool calls remain synchronous. |

The SDK's `ClientCredentialsHandler` is a client-side token acquisition helper,
not resource-server verification. In v1.8.0 it requires a client secret and
selects `client_secret_post` or `client_secret_basic`; it does not implement the
extension's `private_key_jwt` client authentication. The external authorization
server and client determine the token acquisition method. Remaining extension
conformance and interoperability work is tracked in
[issue #919](https://github.com/stackql/stackql/issues/919).

### Breaking change vs PR1

PR1 had a single `read_only: true/false` flag with a default of "no enforcement; mutations proceed." PR2 replaces that flag with `mode: safe` as the default, which means **mutations now require user approval out of the box.** Operators running an elicitation-capable client see one approval prompt per mutation. Operators running automation or the bundled client must explicitly opt into `full_access`.
Expand Down Expand Up @@ -512,3 +568,51 @@ $ ./build/stackql_mcp_client exec --client-type=http --url=http://127.0.0.1:999
{"timestamp":"2026-05-16T00:47:33Z","tool":"run_mutation_query","mode":"full_access","decision":"allow","query_class":"mutation_delete","sql":"delete from google.compute.networks where project = 'stackql-demo' and network = 'returning-test-01' ;","args":{"sql":"delete from google.compute.networks where project = 'stackql-demo' and network = 'returning-test-01' ;","row_limit":0},"duration_ms":42}

```

## OAuth JWT resource-server authentication

OAuth is opt-in for the Streamable HTTP transport. Configure the issuer, audience,
resource URI, JWKS URL, protected-resource metadata URL, required scopes, and
allowed signing algorithms explicitly:

```yaml
server:
transport: http
oauth:
issuer: https://auth.example.com/
audience: https://mcp.example.com/
resource: https://mcp.example.com/
jwks_url: https://auth.example.com/.well-known/jwks.json
# Optional PEM CA bundle for a private authorization server.
# If omitted, the system trust roots are used.
# jwks_ca_file: /etc/stackql/oauth-issuer-ca.pem
metadata_url: https://mcp.example.com/.well-known/oauth-protected-resource
scopes: [stackql:query]
algorithms: [RS256]
cache_ttl: 5m
clock_skew: 30s
```

The metadata URL path is served without credentials. MCP HTTP requests require
a signed JWT with the configured issuer and audience, an expiration, and every
configured scope. Only HTTPS issuer, JWKS, resource, and metadata URLs are
accepted. Redirects are disabled for JWKS fetches. RSA keys must be 2048 to
4096 bits. JWKS bodies, key counts, token sizes, cache duration, and clock skew
are bounded. A fresh JWKS cache is refreshed for an unknown key at most once
per second; publish replacement keys before retiring old keys to allow token
rotation.

An unavailable or invalid JWKS response fails closed as a server error, while
invalid credentials receive an authentication rejection. OAuth cannot be
combined with the pre-shared bearer token, the unauthenticated opt-in, the
embedding authentication hook, or client-certificate authentication. Serve the
protected endpoint over HTTPS, including when TLS terminates at a trusted
reverse proxy.

This resource server verifies signed JWTs only. It does not acquire tokens,
introspect opaque tokens, provide immediate revocation, or support DPoP or
mTLS-bound access tokens. Existing pre-shared bearer-token deployments and
stdio authentication behavior remain available when OAuth is not configured.

MCP response cache metadata is private. List results use a 30-second TTL;
resource content and discovery results are marked immediately stale.
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ require (
github.com/PaesslerAG/gval v1.0.0
github.com/PaesslerAG/jsonpath v0.1.1
github.com/chzyer/readline v1.5.1
github.com/go-jose/go-jose/v4 v4.1.6
github.com/golang-jwt/jwt/v5 v5.3.1
github.com/google/go-jsonnet v0.17.0
github.com/google/licensecheck v0.3.1
Expand Down Expand Up @@ -84,7 +85,6 @@ require (
github.com/fsnotify/fsnotify v1.5.1 // indirect
github.com/fullstorydev/grpcurl v1.9.3 // indirect
github.com/gabriel-vasile/mimetype v1.4.7 // indirect
github.com/go-jose/go-jose/v4 v4.1.6 // indirect
github.com/goccy/go-json v0.10.4 // indirect
github.com/godbus/dbus v0.0.0-20190726142602-4481cbc300e2 // indirect
github.com/golang/glog v1.2.5 // indirect
Expand Down
5 changes: 5 additions & 0 deletions packaging/mcpb/go/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ and pin-verifying the release bundle when absent. Either way it spawns the
binary as an MCP stdio server and hands you a connected client from the
official
[modelcontextprotocol/go-sdk](https://github.com/modelcontextprotocol/go-sdk).
The launcher and StackQL use Go SDK v1.8.0. The client attempts
`2026-07-28` discovery first and falls back to the legacy initialization
handshake when required by the server.

The module is version-locked to the stackql release it embeds: the module
tag is `v<stackql version>` (pin the minor, e.g. `v0.10`), and its
Expand Down Expand Up @@ -139,6 +142,8 @@ go test -short ./... # unit tests
go test ./embed/ # + conformance tests (downloads the release bundle,
# spawns it, exercises the github provider with no
# credentials; ports scripts/smoke-test.py)
STACKQL_MCP_TEST_BINARY=/absolute/path/to/stackql go test ./embed/
# also test current and legacy protocol lifecycles
python scripts/smoke-test.py --cmd "go run -C go ./cmd/stackql-mcp-launch" # from packaging/mcpb
```

Expand Down
42 changes: 41 additions & 1 deletion packaging/mcpb/go/embed/integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,46 @@ func textContent(t *testing.T, res *mcp.CallToolResult) string {
return sb.String()
}

func TestProtocolLifecycleCompatibility(t *testing.T) {
if testing.Short() {
t.Skip("integration test: spawns the embedded server")
}
if os.Getenv("STACKQL_MCP_TEST_BINARY") == "" {
t.Skip("requires a current StackQL binary with protocol version pinning")
}
bin := conformanceBinary(t)
for _, version := range []string{"2026-07-28", "2025-11-25"} {
t.Run(version, func(t *testing.T) {
tmp := t.TempDir()
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
client, err := stackqlmcp.StartServer(ctx, stackqlmcp.Options{
Binary: bin,
AppRoot: filepath.Join(tmp, "app"),
CacheDir: filepath.Join(tmp, "bin-cache"),
ExtraArgs: []string{"--mcp.protocol.version=" + version},
})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
if err := client.Close(); err != nil {
t.Errorf("closing server: %v", err)
}
})
// The SDK populates this from discovery for the handshake-free revision.
result := client.Session.InitializeResult()
if result == nil || result.ServerInfo == nil || result.ProtocolVersion != version {
t.Fatalf("server discovery or initialization: %+v", result)
}
tools, err := client.Session.ListTools(ctx, nil)
if err != nil || len(tools.Tools) == 0 {
t.Fatalf("listing tools: result=%+v err=%v", tools, err)
}
})
}
}

func TestConformanceGithubNullAuth(t *testing.T) {
if testing.Short() {
t.Skip("integration test: spawns the embedded server and reaches registry.stackql.app")
Expand Down Expand Up @@ -109,7 +149,7 @@ func TestConformanceGithubNullAuth(t *testing.T) {
if got := client.Session.InitializeResult(); got == nil || got.ServerInfo == nil {
t.Fatal("initialize returned no server info")
} else {
t.Logf("initialize ok: server=%s %s", got.ServerInfo.Name, got.ServerInfo.Version)
t.Logf("connected: server=%s %s protocol=%s", got.ServerInfo.Name, got.ServerInfo.Version, got.ProtocolVersion)
}

tools, err := client.Session.ListTools(ctx, nil)
Expand Down
4 changes: 3 additions & 1 deletion packaging/mcpb/go/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,15 @@ module github.com/stackql/stackql-mcp-go

go 1.27.3

require github.com/modelcontextprotocol/go-sdk v1.6.1
require github.com/modelcontextprotocol/go-sdk v1.8.0

require (
github.com/google/jsonschema-go v0.4.3 // indirect
github.com/segmentio/asm v1.1.3 // indirect
github.com/segmentio/encoding v0.5.4 // indirect
github.com/yosida95/uritemplate/v3 v3.0.2 // indirect
golang.org/x/oauth2 v0.35.0 // indirect
golang.org/x/sync v0.20.0 // indirect
golang.org/x/sys v0.41.0 // indirect
golang.org/x/time v0.15.0 // indirect
)
8 changes: 6 additions & 2 deletions packaging/mcpb/go/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/jsonschema-go v0.4.3 h1:/DBOLZTfDow7pe2GmaJNhltueGTtDKICi8V8p+DQPd0=
github.com/google/jsonschema-go v0.4.3/go.mod h1:r5quNTdLOYEz95Ru18zA0ydNbBuYoo9tgaYcxEYhJVE=
github.com/modelcontextprotocol/go-sdk v1.6.1 h1:0zOSupjKUxPKSocPT1Wtago+mUHU2/uZ4xSOY0FGReU=
github.com/modelcontextprotocol/go-sdk v1.6.1/go.mod h1:kzm3kzFL1/+AziGOE0nUs3gvPoNxMCvkxokMkuFapXQ=
github.com/modelcontextprotocol/go-sdk v1.8.0 h1:KIvahhYqwtbeniWVPs3TcXEA7b8jEtwfBpOTAI+Urx4=
github.com/modelcontextprotocol/go-sdk v1.8.0/go.mod h1:dL7u98E/zjJTGzEq+j30jQ8K2k1mb6LeAH4inEcSGts=
github.com/segmentio/asm v1.1.3 h1:WM03sfUOENvvKexOLp+pCqgb/WDjsi7EK8gIsICtzhc=
github.com/segmentio/asm v1.1.3/go.mod h1:Ld3L4ZXGNcSLRg4JBsZ3//1+f/TjYl0Mzen/DQy1EJg=
github.com/segmentio/encoding v0.5.4 h1:OW1VRern8Nw6ITAtwSZ7Idrl3MXCFwXHPgqESYfvNt0=
Expand All @@ -14,7 +14,11 @@ github.com/yosida95/uritemplate/v3 v3.0.2 h1:Ed3Oyj9yrmi9087+NczuL5BwkIc4wvTb5zI
github.com/yosida95/uritemplate/v3 v3.0.2/go.mod h1:ILOh0sOhIJR3+L/8afwt/kE++YT040gmv5BQTMR2HP4=
golang.org/x/oauth2 v0.35.0 h1:Mv2mzuHuZuY2+bkyWXIHMfhNdJAdwW3FuWeCPYN5GVQ=
golang.org/x/oauth2 v0.35.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA=
golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=
golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U=
golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno=
golang.org/x/tools v0.42.0 h1:uNgphsn75Tdz5Ji2q36v/nsFSfR/9BRFvqhGBaJGd5k=
golang.org/x/tools v0.42.0/go.mod h1:Ma6lCIwGZvHK6XtgbswSoWroEkhugApmsXyrUmBhfr0=
17 changes: 17 additions & 0 deletions pkg/mcp_server/cache_policy.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package mcp_server //nolint:revive // package name is retained for compatibility

import (
"context"
"time"

"github.com/modelcontextprotocol/go-sdk/mcp"
)

func setCachePolicy(_ context.Context, req mcp.Request, cache *mcp.Cacheable) {
cache.CacheScope = "private"
cache.TTLMs = 0
switch req.(type) {
case *mcp.ListToolsRequest, *mcp.ListPromptsRequest, *mcp.ListResourcesRequest, *mcp.ListResourceTemplatesRequest:
cache.TTLMs = int((30 * time.Second).Milliseconds())
}
}
Loading
Loading