Skip to content

Commit 361895a

Browse files
TMHSDigitalclaude
andcommitted
MCP: encode the tools' input schemas instead of splicing them into JSON text
The lab_scan and scan input schemas were built with fmt.Sprintf, placing marshalled values and plain strings into a hand-written JSON document (CodeQL go/unsafe-quoting, alerts 12-17). The marshalled enums were safe, but the allow-list was joined straight into a quoted description, so a value holding a quote would have produced a broken or altered schema. The schemas are now Go values encoded by encoding/json. schemaObject keeps the properties in the order written; the only bytes written by hand are braces, colons and commas. The served schemas are equivalent, in compact form. A test feeds a value with a quote, backslash and newline through the scan tool's schema and checks it stays inside its string. Co-Authored-By: Claude Mythos 5.2 <noreply@anthropic.com>
1 parent b2bf805 commit 361895a

2 files changed

Lines changed: 133 additions & 43 deletions

File tree

‎internal/cli/mcp.go‎

Lines changed: 83 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -305,14 +305,67 @@ const (
305305
maxMCPExclude = 1000
306306
)
307307

308+
// schemaField is one key of a JSON object whose keys keep the order written.
309+
type schemaField struct {
310+
key string
311+
val any
312+
}
313+
314+
// schemaObject is a JSON object with ordered keys, for the tools' input
315+
// schemas. Every key and value goes through encoding/json and the only bytes
316+
// written by hand are braces, colons and commas, so no name, description or
317+
// enum entry can break out of its string, whatever it contains.
318+
type schemaObject []schemaField
319+
320+
// MarshalJSON writes the fields in order.
321+
func (o schemaObject) MarshalJSON() ([]byte, error) {
322+
var b bytes.Buffer
323+
b.WriteByte('{')
324+
for i, f := range o {
325+
if i > 0 {
326+
b.WriteByte(',')
327+
}
328+
key, err := json.Marshal(f.key)
329+
if err != nil {
330+
return nil, err
331+
}
332+
val, err := json.Marshal(f.val)
333+
if err != nil {
334+
return nil, err
335+
}
336+
b.Write(key)
337+
b.WriteByte(':')
338+
b.Write(val)
339+
}
340+
b.WriteByte('}')
341+
return b.Bytes(), nil
342+
}
343+
344+
// inputSchema is the JSON Schema of a tool's arguments: an object with these
345+
// properties and no others.
346+
func inputSchema(props schemaObject, required ...string) json.RawMessage {
347+
schema := schemaObject{{"type", "object"}, {"properties", props}}
348+
if len(required) > 0 {
349+
schema = append(schema, schemaField{"required", required})
350+
}
351+
schema = append(schema, schemaField{"additionalProperties", false})
352+
raw, _ := json.Marshal(schema) // strings, numbers and booleans only: cannot fail
353+
return raw
354+
}
355+
356+
// wordsSchema is the words argument, with the tool's own description.
357+
func wordsSchema(description string) map[string]any {
358+
return map[string]any{"type": "array", "items": map[string]any{"type": "string"}, "maxItems": maxMCPWords, "description": description}
359+
}
360+
308361
// remediationProps are the scan settings an agent can change after a verdict
309362
// that is not complete (#269). None can raise the operator's caps.
310-
var remediationProps = fmt.Sprintf(`,
311-
"retry_inconclusive": {"type": "boolean", "description": "At the end, look up once more every name that timed out, was refused or failed; an answer replaces the first outcome. Use it when failures degraded the verdict."},
312-
"auto_rate": {"type": "boolean", "description": "Halve the query rate while many lookups fail and raise it again once they succeed, never above the starting rate, instead of giving up."},
313-
"exclude": {"type": "array", "items": {"type": "string"}, "maxItems": %d, "description": "Names out of scope that are never queried: one name (mail.example.com) or a branch (*.corp.example.com)."},
314-
"depth": {"type": "integer", "minimum": 1, "maximum": %d, "description": "Enumerate the words again under every name found, down to this many levels; default 1, no recursion. Every level stays within max_queries."}`,
315-
maxMCPExclude, maxMCPDepth)
363+
var remediationProps = schemaObject{
364+
{"retry_inconclusive", map[string]any{"type": "boolean", "description": "At the end, look up once more every name that timed out, was refused or failed; an answer replaces the first outcome. Use it when failures degraded the verdict."}},
365+
{"auto_rate", map[string]any{"type": "boolean", "description": "Halve the query rate while many lookups fail and raise it again once they succeed, never above the starting rate, instead of giving up."}},
366+
{"exclude", map[string]any{"type": "array", "items": map[string]any{"type": "string"}, "maxItems": maxMCPExclude, "description": "Names out of scope that are never queried: one name (mail.example.com) or a branch (*.corp.example.com)."}},
367+
{"depth", map[string]any{"type": "integer", "minimum": 1, "maximum": maxMCPDepth, "description": "Enumerate the words again under every name found, down to this many levels; default 1, no recursion. Every level stays within max_queries."}},
368+
}
316369

317370
// remediation holds the remediationProps arguments.
318371
type remediation struct {
@@ -338,32 +391,27 @@ func (r remediation) apply(cfg *subenum.Config) error {
338391
}
339392

340393
// recordTypeSchema offers every type -type accepts (#264).
341-
var recordTypeSchema = func() json.RawMessage {
342-
enum, _ := json.Marshal(dns.Types())
343-
return json.RawMessage(`{"type": "array", "items": {"enum": ` + string(enum) + `}, "description": "Record types to look up; default A and AAAA. CNAME and NS add takeover hints."}`)
344-
}()
394+
var recordTypeSchema = map[string]any{
395+
"type": "array",
396+
"items": map[string]any{"enum": dns.Types()},
397+
"description": "Record types to look up; default A and AAAA. CNAME and NS add takeover hints.",
398+
}
345399

346400
func labScanTool(cfg mcpConfig) mcp.Tool {
347-
scenarios, _ := json.Marshal(labScenarios())
348-
scenarioDesc, _ := json.Marshal(fmt.Sprintf("Lab scenario to scan; default lab1-first-scan. Each is a fictional zone for %s served on this machine.%s",
349-
labDomain, labScenarioGuide()))
350-
schema := fmt.Sprintf(`{
351-
"type": "object",
352-
"properties": {
353-
"scenario": {"enum": %s, "description": %s},
354-
"words": {"type": "array", "items": {"type": "string"}, "maxItems": %d, "description": "Subdomain labels to try; default the labs' short wordlist."},
355-
"types": %s,
356-
"rate": {"type": "integer", "minimum": 0, "maximum": 1000, "description": "Queries per second; 0 or absent is unlimited. Lab traffic stays on this machine."},
357-
"max_queries": {"type": "integer", "minimum": 1, "maximum": %d, "description": "Most names to test."},
358-
"force": {"type": "boolean", "description": "Scan a wildcard zone anyway, filtering answers that match the wildcard."}%s
359-
},
360-
"additionalProperties": false
361-
}`, scenarios, scenarioDesc, maxMCPWords, recordTypeSchema, cfg.maxQueries, remediationProps)
401+
schema := inputSchema(append(schemaObject{
402+
{"scenario", map[string]any{"enum": labScenarios(), "description": fmt.Sprintf("Lab scenario to scan; default lab1-first-scan. Each is a fictional zone for %s served on this machine.%s",
403+
labDomain, labScenarioGuide())}},
404+
{"words", wordsSchema("Subdomain labels to try; default the labs' short wordlist.")},
405+
{"types", recordTypeSchema},
406+
{"rate", map[string]any{"type": "integer", "minimum": 0, "maximum": 1000, "description": "Queries per second; 0 or absent is unlimited. Lab traffic stays on this machine."}},
407+
{"max_queries", map[string]any{"type": "integer", "minimum": 1, "maximum": cfg.maxQueries, "description": "Most names to test."}},
408+
{"force", map[string]any{"type": "boolean", "description": "Scan a wildcard zone anyway, filtering answers that match the wildcard."}},
409+
}, remediationProps...))
362410
return mcp.Tool{
363411
Name: "lab_scan",
364412
Title: "Scan a lab zone",
365413
Description: fmt.Sprintf("Enumerate subdomains of %s in one of subenum's lab scenarios: fictional zones answered by a DNS server on this machine, so no traffic leaves it. Safe for practice and for learning how wildcards, rate limits and failing resolvers change a scan's verdict.", labDomain),
366-
InputSchema: json.RawMessage(schema),
414+
InputSchema: schema,
367415
OutputSchema: mcpReportSchema,
368416
Annotations: mcp.Annotations{ReadOnlyHint: true},
369417
Call: func(ctx context.Context, raw json.RawMessage) mcp.Result {
@@ -426,30 +474,23 @@ func labScanTool(cfg mcpConfig) mcp.Tool {
426474
}
427475

428476
func scanTool(cfg mcpConfig) mcp.Tool {
429-
sourcesProp := ""
477+
props := schemaObject{
478+
{"domain", map[string]any{"type": "string", "description": fmt.Sprintf("Domain to enumerate: one of %s, or a subdomain of one.", strings.Join(cfg.allow, ", "))}},
479+
{"words", wordsSchema("Subdomain labels to try; default subenum's bundled list of the most common ones.")},
480+
{"types", recordTypeSchema},
481+
{"max_queries", map[string]any{"type": "integer", "minimum": 1, "maximum": cfg.maxQueries, "description": fmt.Sprintf("Most names to test; default and ceiling %d.", cfg.maxQueries)}},
482+
}
430483
if len(cfg.sources) > 0 {
431-
enum, _ := json.Marshal(cfg.sources)
432-
sourcesProp = fmt.Sprintf(`,
433-
"sources": {"type": "array", "items": {"enum": %s}, "description": "Passive sources to seed candidates from before the scan; default none. Their names are added to words after dedupe, count against max_queries, and are each verified by a lookup. One HTTPS request per source."}`, enum)
484+
props = append(props, schemaField{"sources", map[string]any{"type": "array", "items": map[string]any{"enum": cfg.sources}, "description": "Passive sources to seed candidates from before the scan; default none. Their names are added to words after dedupe, count against max_queries, and are each verified by a lookup. One HTTPS request per source."}})
434485
}
435-
schema := fmt.Sprintf(`{
436-
"type": "object",
437-
"properties": {
438-
"domain": {"type": "string", "description": "Domain to enumerate: one of %s, or a subdomain of one."},
439-
"words": {"type": "array", "items": {"type": "string"}, "maxItems": %d, "description": "Subdomain labels to try; default subenum's bundled list of the most common ones."},
440-
"types": %s,
441-
"max_queries": {"type": "integer", "minimum": 1, "maximum": %d, "description": "Most names to test; default and ceiling %d."}%s%s
442-
},
443-
"required": ["domain"],
444-
"additionalProperties": false
445-
}`, strings.Join(cfg.allow, ", "), maxMCPWords, recordTypeSchema, cfg.maxQueries, cfg.maxQueries, sourcesProp, remediationProps)
486+
schema := inputSchema(append(props, remediationProps...), "domain")
446487
var calls atomic.Int64 // scan calls this session has made
447488
return mcp.Tool{
448489
Name: "scan",
449490
Title: "Enumerate subdomains",
450491
Description: fmt.Sprintf("Enumerate subdomains of a real domain by DNS, through the operator's resolver at %d queries per second, testing at most %d names in %s. Only domains the operator allowed can be scanned: %s.",
451492
cfg.rate, cfg.maxQueries, cfg.maxDuration, strings.Join(cfg.allow, ", ")),
452-
InputSchema: json.RawMessage(schema),
493+
InputSchema: schema,
453494
OutputSchema: mcpReportSchema,
454495
Annotations: mcp.Annotations{ReadOnlyHint: true, OpenWorldHint: true},
455496
Call: func(ctx context.Context, raw json.RawMessage) mcp.Result {

‎internal/cli/mcp_test.go‎

Lines changed: 50 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -502,14 +502,63 @@ func TestTypeAndFormatListsAgree(t *testing.T) {
502502
Enum []string `json:"enum"`
503503
} `json:"items"`
504504
}
505-
if err := json.Unmarshal(recordTypeSchema, &schema); err != nil {
505+
raw, err := json.Marshal(recordTypeSchema)
506+
if err != nil {
507+
t.Fatal(err)
508+
}
509+
if err := json.Unmarshal(raw, &schema); err != nil {
506510
t.Fatal(err)
507511
}
508512
if !slices.Equal(schema.Items.Enum, dns.Types()) {
509513
t.Errorf("MCP types enum %v, want %v", schema.Items.Enum, dns.Types())
510514
}
511515
}
512516

517+
// TestMCPInputSchemaQuoting checks that the tools' input schemas are encoded,
518+
// not spliced together: a value holding a quote, backslash or newline stays
519+
// inside its string, and the properties keep the order they were written in.
520+
func TestMCPInputSchemaQuoting(t *testing.T) {
521+
hostile := `a.example", "injected": {"x": "\` + "\n"
522+
cfg := mcpConfig{maxQueries: 10, allow: []string{hostile}, sources: []string{hostile}}
523+
raw := scanTool(cfg).InputSchema
524+
var schema struct {
525+
Type string `json:"type"`
526+
Properties map[string]struct {
527+
Description string `json:"description"`
528+
Items struct {
529+
Enum []string `json:"enum"`
530+
} `json:"items"`
531+
} `json:"properties"`
532+
Required []string `json:"required"`
533+
AdditionalProperties *bool `json:"additionalProperties"`
534+
}
535+
if err := json.Unmarshal(raw, &schema); err != nil {
536+
t.Fatalf("scan inputSchema is not JSON: %v\n%s", err, raw)
537+
}
538+
if _, ok := schema.Properties["injected"]; ok {
539+
t.Error("a quoted value added a property to the schema")
540+
}
541+
if want := "Domain to enumerate: one of " + hostile + ", or a subdomain of one."; schema.Properties["domain"].Description != want {
542+
t.Errorf("domain description = %q, want %q", schema.Properties["domain"].Description, want)
543+
}
544+
if got := schema.Properties["sources"].Items.Enum; !slices.Equal(got, []string{hostile}) {
545+
t.Errorf("sources enum = %q, want the value unchanged", got)
546+
}
547+
if schema.Type != "object" || !slices.Equal(schema.Required, []string{"domain"}) ||
548+
schema.AdditionalProperties == nil || *schema.AdditionalProperties {
549+
t.Errorf("scan schema envelope = %s", raw)
550+
}
551+
order := []string{`"domain"`, `"words"`, `"types"`, `"max_queries"`, `"sources"`, `"retry_inconclusive"`, `"auto_rate"`, `"exclude"`, `"depth"`}
552+
at := 0
553+
for _, name := range order {
554+
i := strings.Index(string(raw[at:]), name+":")
555+
if i < 0 {
556+
t.Fatalf("property %s missing or out of order in %s", name, raw)
557+
}
558+
at += i
559+
}
560+
}
561+
513562
// TestE2EMCPSessionBudget covers #240: -max-calls caps a session's scan
514563
// calls, so a looping agent cannot multiply -max-queries without end.
515564
func TestE2EMCPSessionBudget(t *testing.T) {

0 commit comments

Comments
 (0)