MCPcopy Create free account
hub / github.com/modelcontextprotocol/go-sdk / TestServerErrors

Function TestServerErrors

mcp/error_test.go:20–112  ·  view source on GitHub ↗

TestServerErrors validates that the server returns appropriate error codes for various invalid requests.

(t *testing.T)

Source from the content-addressed store, hash-verified

18// TestServerErrors validates that the server returns appropriate error codes
19// for various invalid requests.
20func TestServerErrors(t *testing.T) {
21 ctx := context.Background()
22
23 // Set up a server with tools, prompts, and resources for testing
24 cs, _, cleanup := basicConnection(t, func(s *Server) {
25 // Add a tool with required parameters
26 type RequiredParams struct {
27 Name string `json:"name" jsonschema:"the name is required"`
28 }
29 handler := func(ctx context.Context, req *CallToolRequest, args RequiredParams) (*CallToolResult, any, error) {
30 return &CallToolResult{
31 Content: []Content{&TextContent{Text: "success"}},
32 }, nil, nil
33 }
34 AddTool(s, &Tool{Name: "validate", Description: "validates params"}, handler)
35
36 // Add a prompt
37 s.AddPrompt(codeReviewPrompt, codReviewPromptHandler)
38
39 // Add a resource that returns ResourceNotFoundError
40 s.AddResource(
41 &Resource{URI: "file:///test.txt", Name: "test", MIMEType: "text/plain"},
42 func(ctx context.Context, req *ReadResourceRequest) (*ReadResourceResult, error) {
43 return nil, ResourceNotFoundError(req.Params.URI)
44 },
45 )
46 })
47 defer cleanup()
48
49 testCases := []struct {
50 name string
51 executeCall func() error
52 expectedCode int64
53 }{
54 // Note: "missing required param" is tested separately below, because
55 // input validation errors are returned as tool results with IsError=true
56 // rather than JSON-RPC errors (see #450).
57 {
58 name: "unknown tool",
59 executeCall: func() error {
60 _, err := cs.CallTool(ctx, &CallToolParams{
61 Name: "nonexistent_tool",
62 Arguments: map[string]any{},
63 })
64 return err
65 },
66 expectedCode: jsonrpc.CodeInvalidParams,
67 },
68 {
69 name: "unknown prompt",
70 executeCall: func() error {
71 _, err := cs.GetPrompt(ctx, &GetPromptParams{
72 Name: "nonexistent_prompt",
73 Arguments: map[string]string{},
74 })
75 return err
76 },
77 expectedCode: jsonrpc.CodeInvalidParams,

Callers

nothing calls this directly

Calls 10

basicConnectionFunction · 0.85
AddToolFunction · 0.85
ResourceNotFoundErrorFunction · 0.85
AddPromptMethod · 0.80
AddResourceMethod · 0.80
CallToolMethod · 0.80
GetPromptMethod · 0.80
ReadResourceMethod · 0.80
RunMethod · 0.80
ErrorMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…