| 1 |
package main |
| 2 |
|
| 3 |
import ( |
| 4 |
"context" |
| 5 |
"fmt" |
| 6 |
|
| 7 |
"github.com/anthropics/anthropic-sdk-go" |
| 8 |
"github.com/anthropics/anthropic-sdk-go/option" |
| 9 |
"github.com/anthropics/anthropic-sdk-go/packages/param" |
| 10 |
) |
| 11 |
|
| 12 |
func main() { |
| 13 |
client := anthropic.NewClient(option.WithHeader("anthropic-beta", anthropic.AnthropicBetaMCPClient2025_04_04)) |
| 14 |
|
| 15 |
mcpServers := []anthropic.BetaRequestMCPServerURLDefinitionParam{ |
| 16 |
{ |
| 17 |
URL: "http://example-server.modelcontextprotocol.io/sse", |
| 18 |
Name: "example", |
| 19 |
AuthorizationToken: param.NewOpt("YOUR_TOKEN"), |
| 20 |
ToolConfiguration: anthropic.BetaRequestMCPServerToolConfigurationParam{ |
| 21 |
Enabled: anthropic.Bool(true), |
| 22 |
AllowedTools: []string{"echo", "add"}, |
| 23 |
}, |
| 24 |
}, |
| 25 |
} |
| 26 |
|
| 27 |
stream := client.Beta.Messages.NewStreaming(context.TODO(), anthropic.BetaMessageNewParams{ |
| 28 |
MaxTokens: 1024, |
| 29 |
Messages: []anthropic.BetaMessageParam{ |
| 30 |
anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock("what is 1+1?")), |
| 31 |
}, |
| 32 |
MCPServers: mcpServers, |
| 33 |
Model: anthropic.ModelClaudeSonnet4_5_20250929, |
| 34 |
StopSequences: []string{"```\n"}, |
| 35 |
}) |
| 36 |
|
| 37 |
message := anthropic.BetaMessage{} |
| 38 |
for stream.Next() { |
| 39 |
event := stream.Current() |
| 40 |
err := message.Accumulate(event) |
| 41 |
if err != nil { |
| 42 |
fmt.Printf("error accumulating event: %v\n", err) |
| 43 |
continue |
| 44 |
} |
| 45 |
|
| 46 |
switch eventVariant := event.AsAny().(type) { |
| 47 |
case anthropic.BetaRawMessageDeltaEvent: |
| 48 |
print(eventVariant.Delta.StopSequence) |
| 49 |
case anthropic.BetaRawContentBlockDeltaEvent: |
| 50 |
switch deltaVariant := eventVariant.Delta.AsAny().(type) { |
| 51 |
case anthropic.BetaTextDelta: |
| 52 |
print(deltaVariant.Text) |
| 53 |
} |
| 54 |
default: |
| 55 |
fmt.Printf("%+v\n", eventVariant) |
| 56 |
} |
| 57 |
} |
| 58 |
|
| 59 |
println() |
| 60 |
|
| 61 |
if stream.Err() != nil { |
| 62 |
panic(stream.Err()) |
| 63 |
} |
| 64 |
|
| 65 |
} |