|
| 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 | +package mcp_test |
| 6 | + |
| 7 | +import ( |
| 8 | + "context" |
| 9 | + "fmt" |
| 10 | + "log" |
| 11 | + |
| 12 | + "github.com/modelcontextprotocol/go-sdk/mcp" |
| 13 | +) |
| 14 | + |
| 15 | +// !+prompts |
| 16 | + |
| 17 | +func Example_prompts() { |
| 18 | + ctx := context.Background() |
| 19 | + |
| 20 | + promptHandler := func(ctx context.Context, req *mcp.GetPromptRequest) (*mcp.GetPromptResult, error) { |
| 21 | + return &mcp.GetPromptResult{ |
| 22 | + Description: "Hi prompt", |
| 23 | + Messages: []*mcp.PromptMessage{ |
| 24 | + { |
| 25 | + Role: "user", |
| 26 | + Content: &mcp.TextContent{Text: "Say hi to " + req.Params.Arguments["name"]}, |
| 27 | + }, |
| 28 | + }, |
| 29 | + }, nil |
| 30 | + } |
| 31 | + |
| 32 | + // Create a server with a single prompt. |
| 33 | + s := mcp.NewServer(&mcp.Implementation{Name: "server", Version: "v0.0.1"}, nil) |
| 34 | + s.AddPrompt(&mcp.Prompt{Name: "greet"}, promptHandler) |
| 35 | + |
| 36 | + // Create a client. |
| 37 | + c := mcp.NewClient(&mcp.Implementation{Name: "client", Version: "v0.0.1"}, nil) |
| 38 | + |
| 39 | + // Connect the server and client. |
| 40 | + t1, t2 := mcp.NewInMemoryTransports() |
| 41 | + if _, err := s.Connect(ctx, t1, nil); err != nil { |
| 42 | + log.Fatal(err) |
| 43 | + } |
| 44 | + cs, err := c.Connect(ctx, t2, nil) |
| 45 | + if err != nil { |
| 46 | + log.Fatal(err) |
| 47 | + } |
| 48 | + |
| 49 | + // List the prompts. |
| 50 | + for p, err := range cs.Prompts(ctx, nil) { |
| 51 | + if err != nil { |
| 52 | + log.Fatal(err) |
| 53 | + } |
| 54 | + fmt.Println(p.Name) |
| 55 | + } |
| 56 | + |
| 57 | + // Get the prompt. |
| 58 | + res, err := cs.GetPrompt(ctx, &mcp.GetPromptParams{ |
| 59 | + Name: "greet", |
| 60 | + Arguments: map[string]string{"name": "Pat"}, |
| 61 | + }) |
| 62 | + if err != nil { |
| 63 | + log.Fatal(err) |
| 64 | + } |
| 65 | + for _, msg := range res.Messages { |
| 66 | + fmt.Println(msg.Role, msg.Content.(*mcp.TextContent).Text) |
| 67 | + } |
| 68 | + // Output: |
| 69 | + // greet |
| 70 | + // user Say hi to Pat |
| 71 | +} |
| 72 | + |
| 73 | +// !-prompts |
0 commit comments