-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathconfig_stdin.go
More file actions
540 lines (454 loc) · 17.7 KB
/
config_stdin.go
File metadata and controls
540 lines (454 loc) · 17.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
// Package config provides configuration loading and parsing.
// This file defines stdin (JSON) configuration types.
package config
import (
"encoding/json"
"fmt"
"io"
"log"
"os"
"github.com/github/gh-aw-mcpg/internal/logger"
)
var logStdin = logger.New("config:config_stdin")
// StdinConfig represents the JSON configuration format read from stdin.
type StdinConfig struct {
// MCPServers maps server names to their configurations
MCPServers map[string]*StdinServerConfig `json:"mcpServers"`
// Gateway holds global gateway settings
Gateway *StdinGatewayConfig `json:"gateway,omitempty"`
// Guards holds guard configurations for DIFC enforcement
Guards map[string]*StdinGuardConfig `json:"guards,omitempty"`
// CustomSchemas defines custom server types
CustomSchemas map[string]interface{} `json:"customSchemas,omitempty"`
}
// StdinGatewayConfig represents gateway configuration in stdin JSON format.
// Uses pointers for optional fields to distinguish between unset and zero values.
type StdinGatewayConfig struct {
Port *int `json:"port,omitempty"`
APIKey string `json:"apiKey,omitempty"`
Domain string `json:"domain,omitempty"`
StartupTimeout *int `json:"startupTimeout,omitempty"`
ToolTimeout *int `json:"toolTimeout,omitempty"`
KeepaliveInterval *int `json:"keepaliveInterval,omitempty"`
PayloadDir string `json:"payloadDir,omitempty"`
PayloadSizeThreshold *int `json:"payloadSizeThreshold,omitempty"`
TrustedBots []string `json:"trustedBots,omitempty"`
OpenTelemetry *StdinOpenTelemetryConfig `json:"opentelemetry,omitempty"`
}
// StdinOpenTelemetryConfig represents the OpenTelemetry configuration in stdin JSON format (spec §4.1.3.6).
type StdinOpenTelemetryConfig struct {
// Endpoint is the OTLP/HTTP collector URL. MUST be HTTPS. Supports ${VAR} expansion.
Endpoint string `json:"endpoint"`
// Headers are HTTP headers for export requests (e.g. auth tokens). Values support ${VAR}.
Headers map[string]string `json:"headers,omitempty"`
// TraceID is the parent trace ID (32-char lowercase hex, W3C format). Supports ${VAR}.
TraceID string `json:"traceId,omitempty"`
// SpanID is the parent span ID (16-char lowercase hex, W3C format). Ignored without TraceID. Supports ${VAR}.
SpanID string `json:"spanId,omitempty"`
// ServiceName is the service.name resource attribute. Default: "mcp-gateway".
ServiceName string `json:"serviceName,omitempty"`
}
// StdinGuardConfig represents a guard configuration in stdin JSON format.
type StdinGuardConfig struct {
// Type is the guard type: "wasm", "noop", etc.
Type string `json:"type"`
// Path is the path to the guard implementation (e.g., WASM file)
Path string `json:"path,omitempty"`
// Config holds guard-specific configuration
Config map[string]interface{} `json:"config,omitempty"`
// Policy holds guard policy configuration for label_agent lifecycle initialization
Policy *GuardPolicy `json:"policy,omitempty"`
}
// StdinServerConfig represents a single server configuration in stdin JSON format.
type StdinServerConfig struct {
// Type is the server type: "stdio", "local", or "http"
Type string `json:"type"`
// Container is the Docker image for stdio servers
Container string `json:"container,omitempty"`
// Entrypoint overrides the container entrypoint
Entrypoint string `json:"entrypoint,omitempty"`
// EntrypointArgs are additional arguments to the entrypoint
EntrypointArgs []string `json:"entrypointArgs,omitempty"`
// Args are additional Docker runtime arguments (passed before container image)
Args []string `json:"args,omitempty"`
// Mounts are volume mounts for the container
Mounts []string `json:"mounts,omitempty"`
// Env holds environment variables
Env map[string]string `json:"env,omitempty"`
// URL is the HTTP endpoint (for http servers)
URL string `json:"url,omitempty"`
// Headers are HTTP headers to send (for http servers)
Headers map[string]string `json:"headers,omitempty"`
// Tools is an optional list of tools to filter/expose
Tools []string `json:"tools,omitempty"`
// Registry is the URI to the installation location in an MCP registry (informational)
Registry string `json:"registry,omitempty"`
// GuardPolicies holds guard policies for access control at the MCP gateway level.
// The structure is server-specific. For GitHub MCP server, see the GitHub guard policy schema.
GuardPolicies map[string]interface{} `json:"guard-policies,omitempty"`
// Guard is the name of the guard to use for this server (requires DIFC)
Guard string `json:"guard,omitempty"`
// Auth configures upstream authentication for HTTP MCP servers.
Auth *AuthConfig `json:"auth,omitempty"`
// AdditionalProperties stores any extra fields for custom server types
// This allows custom schemas to define their own fields beyond the standard ones
AdditionalProperties map[string]interface{} `json:"-"`
}
// UnmarshalJSON implements custom JSON unmarshaling to capture additional properties
func (s *StdinServerConfig) UnmarshalJSON(data []byte) error {
// Define an auxiliary type to avoid infinite recursion
type Alias StdinServerConfig
aux := &struct {
*Alias
}{
Alias: (*Alias)(s),
}
// Unmarshal into the auxiliary struct first
if err := json.Unmarshal(data, &aux); err != nil {
return err
}
// Now unmarshal into a map to capture all fields
var allFields map[string]interface{}
if err := json.Unmarshal(data, &allFields); err != nil {
return err
}
// Known fields in the struct
knownFields := map[string]bool{
"type": true,
"container": true,
"entrypoint": true,
"entrypointArgs": true,
"args": true,
"mounts": true,
"env": true,
"url": true,
"headers": true,
"tools": true,
"registry": true,
"guard-policies": true,
"guard": true,
"auth": true,
}
// Store additional properties (fields not in the struct)
s.AdditionalProperties = make(map[string]interface{})
for key, value := range allFields {
if !knownFields[key] {
s.AdditionalProperties[key] = value
}
}
return nil
}
// intPtrOrDefault returns the value of the int pointer if not nil, otherwise returns the default value.
// This helper reduces code duplication when handling optional integer fields with defaults.
func intPtrOrDefault(ptr *int, defaultValue int) int {
if ptr != nil {
return *ptr
}
return defaultValue
}
// stripExtensionFieldsForValidation returns a copy of the raw JSON with known gateway
// extension fields removed, so the copy can be validated against the upstream MCP Gateway
// schema. These fields are gateway-specific additions that are not part of the upstream
// schema definition, so they must be removed before schema validation to prevent spurious
// "additional properties" errors.
//
// Fields stripped:
// - Top-level "guards": gateway-specific guard configuration
// - Per-server "guard": reference to a named guard
// - Per-server "auth": upstream authentication configuration (OIDC etc.)
//
// Note: "guard-policies" and "registry" are already injected into the upstream schema
// by fetchAndFixSchema, so they do not need to be stripped here.
func stripExtensionFieldsForValidation(data []byte) ([]byte, error) {
var config map[string]interface{}
if err := json.Unmarshal(data, &config); err != nil {
return nil, err
}
// Strip top-level "guards" extension field
delete(config, "guards")
// Strip per-server "guard" and "auth" extension fields
if servers, ok := config["mcpServers"].(map[string]interface{}); ok {
for _, server := range servers {
if serverMap, ok := server.(map[string]interface{}); ok {
delete(serverMap, "guard")
delete(serverMap, "auth")
}
}
}
return json.Marshal(config)
}
// LoadFromStdin loads configuration from stdin JSON.
func LoadFromStdin() (*Config, error) {
logConfig.Print("Loading configuration from stdin JSON")
data, err := io.ReadAll(os.Stdin)
if err != nil {
return nil, fmt.Errorf("failed to read stdin: %w", err)
}
logConfig.Printf("Read %d bytes from stdin", len(data))
// Pre-process: normalize "local" type to "stdio" for backward compatibility
// This must happen before schema validation since schema only accepts "stdio" or "http"
data, err = normalizeLocalType(data)
if err != nil {
return nil, fmt.Errorf("failed to normalize configuration: %w", err)
}
// Pre-process: expand ${VAR} expressions before schema validation
// This ensures the schema validates expanded values, not variable syntax
data, err = ExpandRawJSONVariables(data)
if err != nil {
return nil, err
}
// Validate against JSON schema (fail-fast, spec-compliant).
// Extension fields "guard" (per-server) and "guards" (top-level) are stripped from
// a copy of the data before validation because they are not in the upstream schema.
// "guard-policies" and "registry" are already injected into the schema by fetchAndFixSchema.
validationData, err := stripExtensionFieldsForValidation(data)
if err != nil {
return nil, fmt.Errorf("failed to prepare data for schema validation: %w", err)
}
if err := validateJSONSchema(validationData); err != nil {
return nil, err
}
var stdinCfg StdinConfig
if err := json.Unmarshal(data, &stdinCfg); err != nil {
return nil, fmt.Errorf("failed to parse JSON: %w", err)
}
logConfig.Printf("Parsed stdin config with %d servers", len(stdinCfg.MCPServers))
// Validate string patterns from schema (regex constraints)
if err := validateStringPatterns(&stdinCfg); err != nil {
return nil, err
}
// Validate customSchemas field (reserved type names check)
if err := validateCustomSchemas(stdinCfg.CustomSchemas); err != nil {
return nil, err
}
// Validate gateway configuration (additional checks)
if err := validateGatewayConfig(stdinCfg.Gateway); err != nil {
return nil, err
}
// Convert stdin config to internal format
cfg, err := convertStdinConfig(&stdinCfg)
if err != nil {
return nil, err
}
logConfig.Printf("Converted stdin config to internal format with %d servers", len(cfg.Servers))
return cfg, nil
}
// convertStdinConfig converts StdinConfig to internal Config format.
func convertStdinConfig(stdinCfg *StdinConfig) (*Config, error) {
logStdin.Printf("Converting stdin config: %d servers", len(stdinCfg.MCPServers))
cfg := &Config{
Servers: make(map[string]*ServerConfig),
}
// Convert gateway config with defaults
if stdinCfg.Gateway != nil {
cfg.Gateway = &GatewayConfig{
Port: intPtrOrDefault(stdinCfg.Gateway.Port, DefaultPort),
APIKey: stdinCfg.Gateway.APIKey,
Domain: stdinCfg.Gateway.Domain,
StartupTimeout: intPtrOrDefault(stdinCfg.Gateway.StartupTimeout, DefaultStartupTimeout),
ToolTimeout: intPtrOrDefault(stdinCfg.Gateway.ToolTimeout, DefaultToolTimeout),
KeepaliveInterval: intPtrOrDefault(stdinCfg.Gateway.KeepaliveInterval, DefaultKeepaliveInterval),
}
if stdinCfg.Gateway.PayloadDir != "" {
cfg.Gateway.PayloadDir = stdinCfg.Gateway.PayloadDir
}
if stdinCfg.Gateway.PayloadSizeThreshold != nil {
cfg.Gateway.PayloadSizeThreshold = *stdinCfg.Gateway.PayloadSizeThreshold
}
if stdinCfg.Gateway.TrustedBots != nil {
if err := validateTrustedBots(stdinCfg.Gateway.TrustedBots); err != nil {
return nil, err
}
cfg.Gateway.TrustedBots = stdinCfg.Gateway.TrustedBots
}
} else {
logStdin.Print("No gateway config in stdin, applying defaults")
cfg.Gateway = &GatewayConfig{}
applyGatewayDefaults(cfg.Gateway)
}
// Apply feature-specific defaults
applyDefaults(cfg)
// Convert servers
for name, server := range stdinCfg.MCPServers {
serverCfg, err := convertStdinServerConfig(name, server, stdinCfg.CustomSchemas)
if err != nil {
return nil, err
}
cfg.Servers[name] = serverCfg
}
// Convert guards
if len(stdinCfg.Guards) > 0 {
logStdin.Printf("Converting %d guard configuration(s)", len(stdinCfg.Guards))
cfg.Guards = make(map[string]*GuardConfig)
for name, guard := range stdinCfg.Guards {
logStdin.Printf("Registering guard: name=%s, type=%s", name, guard.Type)
cfg.Guards[name] = &GuardConfig{
Type: guard.Type,
Path: guard.Path,
Config: guard.Config,
Policy: guard.Policy,
}
}
}
// Apply feature-specific stdin conversions
applyStdinConverters(cfg, stdinCfg)
if err := validateGuardPolicies(cfg); err != nil {
return nil, err
}
return cfg, nil
}
// convertStdinServerConfig converts a single StdinServerConfig to ServerConfig.
func convertStdinServerConfig(name string, server *StdinServerConfig, customSchemas map[string]interface{}) (*ServerConfig, error) {
// Validate server configuration (fail-fast) with custom schemas support
if err := validateServerConfigWithCustomSchemas(name, server, customSchemas); err != nil {
return nil, err
}
// Expand variable expressions in env vars (fail-fast on undefined vars)
if len(server.Env) > 0 {
logStdin.Printf("Server %q: expanding %d environment variable(s)", name, len(server.Env))
expandedEnv, err := expandEnvVariables(server.Env, name)
if err != nil {
return nil, err
}
server.Env = expandedEnv
}
// Expand variable expressions in HTTP headers (fail-fast on undefined vars)
if len(server.Headers) > 0 {
logStdin.Printf("Server %q: expanding %d HTTP header(s)", name, len(server.Headers))
expandedHeaders, err := expandEnvVariables(server.Headers, name)
if err != nil {
return nil, err
}
server.Headers = expandedHeaders
}
// Normalize type: "local" is an alias for "stdio" (backward compatibility)
serverType := server.Type
if serverType == "" {
serverType = "stdio"
}
if serverType == "local" {
serverType = "stdio"
}
logStdin.Printf("Converting server %q: type=%s", name, serverType)
// Handle HTTP servers
if serverType == "http" {
logConfig.Printf("Configured HTTP MCP server: name=%s, url=%s", name, server.URL)
log.Printf("[CONFIG] Configured HTTP MCP server: %s -> %s", name, server.URL)
serverCfg := &ServerConfig{
Type: "http",
URL: server.URL,
Headers: server.Headers,
Tools: server.Tools,
Registry: server.Registry,
GuardPolicies: server.GuardPolicies,
Guard: server.Guard,
}
if server.Auth != nil {
serverCfg.Auth = &AuthConfig{
Type: server.Auth.Type,
Audience: server.Auth.Audience,
}
// Default audience to server URL if not specified
if serverCfg.Auth.Audience == "" {
serverCfg.Auth.Audience = server.URL
}
}
return serverCfg, nil
}
// stdio/local servers only from this point
// All stdio servers use Docker containers
return buildStdioServerConfig(name, server), nil
}
// buildStdioServerConfig builds a ServerConfig for a stdio server.
func buildStdioServerConfig(name string, server *StdinServerConfig) *ServerConfig {
args := []string{
"run",
"--rm",
"-i",
// Standard environment variables for better Docker compatibility
"-e", "NO_COLOR=1",
"-e", "TERM=dumb",
"-e", "PYTHONUNBUFFERED=1",
}
// Add entrypoint override if specified
if server.Entrypoint != "" {
logStdin.Printf("Server %q: using custom entrypoint %q", name, server.Entrypoint)
args = append(args, "--entrypoint", server.Entrypoint)
}
// Add volume mounts if specified
for _, mount := range server.Mounts {
args = append(args, "-v", mount)
}
if len(server.Mounts) > 0 {
logStdin.Printf("Server %q: added %d volume mount(s)", name, len(server.Mounts))
}
// Add user-specified environment variables
// Empty string "" means passthrough from host (just -e KEY)
// Non-empty string means explicit value (-e KEY=value)
for k, v := range server.Env {
args = append(args, "-e")
if v == "" {
// Passthrough from host environment
args = append(args, k)
} else {
// Explicit value
args = append(args, fmt.Sprintf("%s=%s", k, v))
}
}
// Add additional Docker runtime arguments (passed before container image)
// e.g., "--network", "host"
args = append(args, server.Args...)
// Add container name
args = append(args, server.Container)
// Add entrypoint args
args = append(args, server.EntrypointArgs...)
logStdin.Printf("Server %q: configured stdio container=%s, env_vars=%d, mounts=%d", name, server.Container, len(server.Env), len(server.Mounts))
logConfig.Printf("Configured stdio MCP server: name=%s, container=%s", name, server.Container)
return &ServerConfig{
Type: "stdio",
Command: "docker",
Args: args,
Env: make(map[string]string),
Tools: server.Tools,
Registry: server.Registry,
GuardPolicies: server.GuardPolicies,
Guard: server.Guard,
}
}
// normalizeLocalType normalizes "local" type to "stdio" for backward compatibility.
// This allows the configuration to pass schema validation which only accepts "stdio" or "http".
func normalizeLocalType(data []byte) ([]byte, error) {
var rawConfig map[string]interface{}
if err := json.Unmarshal(data, &rawConfig); err != nil {
return nil, err
}
// Check if mcpServers exists
mcpServers, ok := rawConfig["mcpServers"]
if !ok {
return data, nil // No mcpServers, return as is
}
servers, ok := mcpServers.(map[string]interface{})
if !ok {
return data, nil // mcpServers is not a map, return as is
}
// Iterate through servers and normalize "local" to "stdio"
modified := false
for _, serverConfig := range servers {
server, ok := serverConfig.(map[string]interface{})
if !ok {
continue
}
if typeVal, exists := server["type"]; exists {
if typeStr, ok := typeVal.(string); ok && typeStr == "local" {
server["type"] = "stdio"
modified = true
}
}
}
// If we modified anything, re-marshal the data
if modified {
logStdin.Print("Normalized 'local' server type to 'stdio' for backward compatibility")
return json.Marshal(rawConfig)
}
return data, nil
}