Debian Codegraph @

debian/go/src/github.com/modelcontextprotocol/go-sdk/mcp/content.go

raw symbols SCIP
1 // Copyright 2025 The Go MCP SDK Authors. All rights reserved.
2 // Use of this source code is governed by an MIT-style
3 // license that can be found in the LICENSE file.
4
5 // TODO(findleyr): update JSON marshalling of all content types to preserve required fields.
6 // (See [TextContent.MarshalJSON], which handles this for text content).
7
8 package mcp
9
10 import (
11 "encoding/json"
12 "fmt"
13
14 internaljson "github.com/modelcontextprotocol/go-sdk/internal/json"
15 )
16
17 // A Content is a [TextContent], [ImageContent], [AudioContent],
18 // [ResourceLink], [EmbeddedResource], [ToolUseContent], or [ToolResultContent].
19 //
20 // Note: [ToolUseContent] and [ToolResultContent] are only valid in sampling
21 // message contexts (CreateMessageParams/CreateMessageResult).
22 type Content interface {
23 MarshalJSON() ([]byte, error)
24 fromWire(*wireContent)
25 }
26
27 // TextContent is a textual content.
28 type TextContent struct {
29 Text string
30 Meta Meta
31 Annotations *Annotations
32 }
33
34 func (c *TextContent) MarshalJSON() ([]byte, error) {
35 // Custom wire format to ensure the required "text" field is always included, even when empty.
36 wire := struct {
37 Type string `json:"type"`
38 Text string `json:"text"`
39 Meta Meta `json:"_meta,omitempty"`
40 Annotations *Annotations `json:"annotations,omitempty"`
41 }{
42 Type: "text",
43 Text: c.Text,
44 Meta: c.Meta,
45 Annotations: c.Annotations,
46 }
47 return json.Marshal(wire)
48 }
49
50 func (c *TextContent) fromWire(wire *wireContent) {
51 c.Text = wire.Text
52 c.Meta = wire.Meta
53 c.Annotations = wire.Annotations
54 }
55
56 // ImageContent contains base64-encoded image data.
57 type ImageContent struct {
58 Meta Meta
59 Annotations *Annotations
60 Data []byte // base64-encoded
61 MIMEType string
62 }
63
64 func (c *ImageContent) MarshalJSON() ([]byte, error) {
65 // Custom wire format to ensure required fields are always included, even when empty.
66 data := c.Data
67 if data == nil {
68 data = []byte{}
69 }
70 wire := imageAudioWire{
71 Type: "image",
72 MIMEType: c.MIMEType,
73 Data: data,
74 Meta: c.Meta,
75 Annotations: c.Annotations,
76 }
77 return json.Marshal(wire)
78 }
79
80 func (c *ImageContent) fromWire(wire *wireContent) {
81 c.MIMEType = wire.MIMEType
82 c.Data = wire.Data
83 c.Meta = wire.Meta
84 c.Annotations = wire.Annotations
85 }
86
87 // AudioContent contains base64-encoded audio data.
88 type AudioContent struct {
89 Data []byte
90 MIMEType string
91 Meta Meta
92 Annotations *Annotations
93 }
94
95 func (c AudioContent) MarshalJSON() ([]byte, error) {
96 // Custom wire format to ensure required fields are always included, even when empty.
97 data := c.Data
98 if data == nil {
99 data = []byte{}
100 }
101 wire := imageAudioWire{
102 Type: "audio",
103 MIMEType: c.MIMEType,
104 Data: data,
105 Meta: c.Meta,
106 Annotations: c.Annotations,
107 }
108 return json.Marshal(wire)
109 }
110
111 func (c *AudioContent) fromWire(wire *wireContent) {
112 c.MIMEType = wire.MIMEType
113 c.Data = wire.Data
114 c.Meta = wire.Meta
115 c.Annotations = wire.Annotations
116 }
117
118 // Custom wire format to ensure required fields are always included, even when empty.
119 type imageAudioWire struct {
120 Type string `json:"type"`
121 MIMEType string `json:"mimeType"`
122 Data []byte `json:"data"`
123 Meta Meta `json:"_meta,omitempty"`
124 Annotations *Annotations `json:"annotations,omitempty"`
125 }
126
127 // ResourceLink is a link to a resource
128 type ResourceLink struct {
129 URI string
130 Name string
131 Title string
132 Description string
133 MIMEType string
134 Size *int64
135 Meta Meta
136 Annotations *Annotations
137 // Icons for the resource link, if any.
138 Icons []Icon `json:"icons,omitempty"`
139 }
140
141 func (c *ResourceLink) MarshalJSON() ([]byte, error) {
142 return json.Marshal(&wireContent{
143 Type: "resource_link",
144 URI: c.URI,
145 Name: c.Name,
146 Title: c.Title,
147 Description: c.Description,
148 MIMEType: c.MIMEType,
149 Size: c.Size,
150 Meta: c.Meta,
151 Annotations: c.Annotations,
152 Icons: c.Icons,
153 })
154 }
155
156 func (c *ResourceLink) fromWire(wire *wireContent) {
157 c.URI = wire.URI
158 c.Name = wire.Name
159 c.Title = wire.Title
160 c.Description = wire.Description
161 c.MIMEType = wire.MIMEType
162 c.Size = wire.Size
163 c.Meta = wire.Meta
164 c.Annotations = wire.Annotations
165 c.Icons = wire.Icons
166 }
167
168 // EmbeddedResource contains embedded resources.
169 type EmbeddedResource struct {
170 Resource *ResourceContents
171 Meta Meta
172 Annotations *Annotations
173 }
174
175 func (c *EmbeddedResource) MarshalJSON() ([]byte, error) {
176 return json.Marshal(&wireContent{
177 Type: "resource",
178 Resource: c.Resource,
179 Meta: c.Meta,
180 Annotations: c.Annotations,
181 })
182 }
183
184 func (c *EmbeddedResource) fromWire(wire *wireContent) {
185 c.Resource = wire.Resource
186 c.Meta = wire.Meta
187 c.Annotations = wire.Annotations
188 }
189
190 // ToolUseContent represents a request from the assistant to invoke a tool.
191 // This content type is only valid in sampling messages.
192 type ToolUseContent struct {
193 // ID is a unique identifier for this tool use, used to match with ToolResultContent.
194 ID string
195 // Name is the name of the tool to invoke.
196 Name string
197 // Input contains the tool arguments as a JSON object.
198 Input map[string]any
199 Meta Meta
200 }
201
202 func (c *ToolUseContent) MarshalJSON() ([]byte, error) {
203 input := c.Input
204 if input == nil {
205 input = map[string]any{}
206 }
207 wire := struct {
208 Type string `json:"type"`
209 ID string `json:"id"`
210 Name string `json:"name"`
211 Input map[string]any `json:"input"`
212 Meta Meta `json:"_meta,omitempty"`
213 }{
214 Type: "tool_use",
215 ID: c.ID,
216 Name: c.Name,
217 Input: input,
218 Meta: c.Meta,
219 }
220 return json.Marshal(wire)
221 }
222
223 func (c *ToolUseContent) fromWire(wire *wireContent) {
224 c.ID = wire.ID
225 c.Name = wire.Name
226 c.Input = wire.Input
227 c.Meta = wire.Meta
228 }
229
230 // ToolResultContent represents the result of a tool invocation.
231 // This content type is only valid in sampling messages with role "user".
232 type ToolResultContent struct {
233 // ToolUseID references the ID from the corresponding ToolUseContent.
234 ToolUseID string
235 // Content holds the unstructured result of the tool call.
236 Content []Content
237 // StructuredContent holds an optional structured result as a JSON object.
238 StructuredContent any
239 // IsError indicates whether the tool call ended in an error.
240 IsError bool
241 Meta Meta
242 }
243
244 func (c *ToolResultContent) MarshalJSON() ([]byte, error) {
245 // Marshal nested content
246 var contentWire []*wireContent
247 for _, content := range c.Content {
248 data, err := content.MarshalJSON()
249 if err != nil {
250 return nil, err
251 }
252 var w wireContent
253 if err := internaljson.Unmarshal(data, &w); err != nil {
254 return nil, err
255 }
256 contentWire = append(contentWire, &w)
257 }
258 if contentWire == nil {
259 contentWire = []*wireContent{} // avoid JSON null
260 }
261
262 wire := struct {
263 Type string `json:"type"`
264 ToolUseID string `json:"toolUseId"`
265 Content []*wireContent `json:"content"`
266 StructuredContent any `json:"structuredContent,omitempty"`
267 IsError bool `json:"isError,omitempty"`
268 Meta Meta `json:"_meta,omitempty"`
269 }{
270 Type: "tool_result",
271 ToolUseID: c.ToolUseID,
272 Content: contentWire,
273 StructuredContent: c.StructuredContent,
274 IsError: c.IsError,
275 Meta: c.Meta,
276 }
277 return json.Marshal(wire)
278 }
279
280 func (c *ToolResultContent) fromWire(wire *wireContent) {
281 c.ToolUseID = wire.ToolUseID
282 c.StructuredContent = wire.StructuredContent
283 c.IsError = wire.IsError
284 c.Meta = wire.Meta
285 // Content is handled separately in contentFromWire due to nested content
286 }
287
288 // ResourceContents contains the contents of a specific resource or
289 // sub-resource.
290 type ResourceContents struct {
291 URI string `json:"uri"`
292 MIMEType string `json:"mimeType,omitempty"`
293 Text string `json:"text,omitempty"`
294 Blob []byte `json:"blob,omitzero"`
295 Meta Meta `json:"_meta,omitempty"`
296 }
297
298 // wireContent is the wire format for content.
299 // It represents the protocol types TextContent, ImageContent, AudioContent,
300 // ResourceLink, EmbeddedResource, ToolUseContent, and ToolResultContent.
301 // The Type field distinguishes them. In the protocol, each type has a constant
302 // value for the field.
303 type wireContent struct {
304 Type string `json:"type"`
305 Text string `json:"text,omitempty"` // TextContent
306 MIMEType string `json:"mimeType,omitempty"` // ImageContent, AudioContent, ResourceLink
307 Data []byte `json:"data,omitempty"` // ImageContent, AudioContent
308 Resource *ResourceContents `json:"resource,omitempty"` // EmbeddedResource
309 URI string `json:"uri,omitempty"` // ResourceLink
310 Name string `json:"name,omitempty"` // ResourceLink, ToolUseContent
311 Title string `json:"title,omitempty"` // ResourceLink
312 Description string `json:"description,omitempty"` // ResourceLink
313 Size *int64 `json:"size,omitempty"` // ResourceLink
314 Meta Meta `json:"_meta,omitempty"` // all types
315 Annotations *Annotations `json:"annotations,omitempty"` // all types except ToolUseContent, ToolResultContent
316 Icons []Icon `json:"icons,omitempty"` // ResourceLink
317 ID string `json:"id,omitempty"` // ToolUseContent
318 Input map[string]any `json:"input,omitempty"` // ToolUseContent
319 ToolUseID string `json:"toolUseId,omitempty"` // ToolResultContent
320 NestedContent []*wireContent `json:"content,omitempty"` // ToolResultContent
321 StructuredContent any `json:"structuredContent,omitempty"` // ToolResultContent
322 IsError bool `json:"isError,omitempty"` // ToolResultContent
323 }
324
325 // unmarshalContent unmarshals JSON that is either a single content object or
326 // an array of content objects. A single object is wrapped in a one-element slice.
327 func unmarshalContent(raw json.RawMessage, allow map[string]bool) ([]Content, error) {
328 if len(raw) == 0 || string(raw) == "null" {
329 return nil, fmt.Errorf("nil content")
330 }
331 // Try array first, then fall back to single object.
332 var wires []*wireContent
333 if err := internaljson.Unmarshal(raw, &wires); err == nil {
334 return contentsFromWire(wires, allow)
335 }
336 var wire wireContent
337 if err := internaljson.Unmarshal(raw, &wire); err != nil {
338 return nil, err
339 }
340 c, err := contentFromWire(&wire, allow)
341 if err != nil {
342 return nil, err
343 }
344 return []Content{c}, nil
345 }
346
347 func contentsFromWire(wires []*wireContent, allow map[string]bool) ([]Content, error) {
348 blocks := make([]Content, 0, len(wires))
349 for _, wire := range wires {
350 block, err := contentFromWire(wire, allow)
351 if err != nil {
352 return nil, err
353 }
354 blocks = append(blocks, block)
355 }
356 return blocks, nil
357 }
358
359 func contentFromWire(wire *wireContent, allow map[string]bool) (Content, error) {
360 if wire == nil {
361 return nil, fmt.Errorf("nil content")
362 }
363 if allow != nil && !allow[wire.Type] {
364 return nil, fmt.Errorf("invalid content type %q", wire.Type)
365 }
366 switch wire.Type {
367 case "text":
368 v := new(TextContent)
369 v.fromWire(wire)
370 return v, nil
371 case "image":
372 v := new(ImageContent)
373 v.fromWire(wire)
374 return v, nil
375 case "audio":
376 v := new(AudioContent)
377 v.fromWire(wire)
378 return v, nil
379 case "resource_link":
380 v := new(ResourceLink)
381 v.fromWire(wire)
382 return v, nil
383 case "resource":
384 v := new(EmbeddedResource)
385 v.fromWire(wire)
386 return v, nil
387 case "tool_use":
388 v := new(ToolUseContent)
389 v.fromWire(wire)
390 return v, nil
391 case "tool_result":
392 v := new(ToolResultContent)
393 v.fromWire(wire)
394 // Handle nested content - tool_result content can contain text, image, audio,
395 // resource_link, and resource (same as CallToolResult.content)
396 if wire.NestedContent != nil {
397 toolResultContentAllow := map[string]bool{
398 "text": true, "image": true, "audio": true,
399 "resource_link": true, "resource": true,
400 }
401 nestedContent, err := contentsFromWire(wire.NestedContent, toolResultContentAllow)
402 if err != nil {
403 return nil, fmt.Errorf("tool_result nested content: %w", err)
404 }
405 v.Content = nestedContent
406 }
407 return v, nil
408 }
409 return nil, fmt.Errorf("unrecognized content type %q", wire.Type)
410 }