-
Notifications
You must be signed in to change notification settings - Fork 38
Expand file tree
/
Copy pathmain.go
More file actions
312 lines (258 loc) · 9.21 KB
/
Copy pathmain.go
File metadata and controls
312 lines (258 loc) · 9.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
// Tencent is pleased to support the open source community by making trpc-a2a-go available.
//
// Copyright (C) 2025 Tencent. All rights reserved.
//
// trpc-a2a-go is licensed under the Apache License Version 2.0.
// Package main provides example code for using different authentication methods with the A2A client.
package main
import (
"context"
"flag"
"fmt"
"log"
"os"
"strings"
"time"
"golang.org/x/oauth2/clientcredentials"
"trpc.group/trpc-go/trpc-a2a-go/auth"
"trpc.group/trpc-go/trpc-a2a-go/client"
"trpc.group/trpc-go/trpc-a2a-go/protocol"
)
// config holds the client configuration options.
type config struct {
AuthMethod string
AgentURL string
Timeout time.Duration
// JWT Auth options
JWTSecret string
JWTSecretFile string
JWTAudience string
JWTIssuer string
JWTExpiry time.Duration
// API Key options
APIKey string
APIKeyHeader string
// OAuth2 options
OAuth2ClientID string
OAuth2ClientSecret string
OAuth2TokenURL string
OAuth2Scopes string
// Task options
TaskID string
TaskMessage string
SessionID string
}
// parseFlags parses command-line flags and returns a Config.
func parseFlags() config {
var config config
// Basic options
flag.StringVar(&config.AuthMethod, "auth", "jwt", "Authentication method (jwt, apikey, oauth2)")
flag.StringVar(&config.AgentURL, "url", "http://localhost:8080/", "Target A2A agent URL")
flag.DurationVar(&config.Timeout, "timeout", 60*time.Second, "Request timeout")
// JWT options
flag.StringVar(&config.JWTSecret, "jwt-secret", "my-secret-key", "JWT secret key")
flag.StringVar(&config.JWTSecretFile, "jwt-secret-file", "../server/jwt-secret.key", "File containing JWT secret key")
flag.StringVar(&config.JWTAudience, "jwt-audience", "a2a-server", "JWT audience")
flag.StringVar(&config.JWTIssuer, "jwt-issuer", "example", "JWT issuer")
flag.DurationVar(&config.JWTExpiry, "jwt-expiry", 1*time.Hour, "JWT expiration time")
// API Key options
flag.StringVar(&config.APIKey, "api-key", "test-api-key", "API key")
flag.StringVar(&config.APIKeyHeader, "api-key-header", "X-API-Key", "API key header name")
// OAuth2 options
flag.StringVar(&config.OAuth2ClientID, "oauth2-client-id", "my-client-id", "OAuth2 client ID")
flag.StringVar(&config.OAuth2ClientSecret, "oauth2-client-secret", "my-client-secret", "OAuth2 client secret")
flag.StringVar(&config.OAuth2TokenURL, "oauth2-token-url", "", "OAuth2 token URL (default: derived from agent URL)")
flag.StringVar(&config.OAuth2Scopes, "oauth2-scopes", "a2a.read,a2a.write", "OAuth2 scopes (comma-separated)")
// Task options
flag.StringVar(&config.TaskID, "task-id", "auth-test-task", "ID for the task to send")
flag.StringVar(&config.TaskMessage, "message", "Hello, this is an authenticated request", "Message to send")
flag.StringVar(&config.SessionID, "session-id", "", "Optional session ID for the task")
flag.Parse()
return config
}
func main() {
config := parseFlags()
if config.AuthMethod == "" {
flag.Usage()
return
}
var a2aClient *client.A2AClient
var err error
// Create client with the specified authentication method
switch config.AuthMethod {
case "jwt":
a2aClient, err = createJWTClient(config)
case "apikey":
a2aClient, err = createAPIKeyClient(config)
case "oauth2":
a2aClient, err = createOAuth2Client(config)
default:
fmt.Printf("Unknown authentication method: %s\n", config.AuthMethod)
return
}
if err != nil {
log.Fatalf("Failed to create client: %v", err)
}
// Create a simple task to test authentication
textPart := protocol.NewTextPart(config.TaskMessage)
message := protocol.NewMessage(protocol.MessageRoleUser, []protocol.Part{textPart})
// Prepare message parameters
params := protocol.SendMessageParams{
Message: message,
}
// Add context ID if session ID is provided
if config.SessionID != "" {
// In the new protocol, we use contextID instead of sessionID
params.Message.ContextID = &config.SessionID
}
agentCard, err := a2aClient.GetAuthenticatedExtendedCard(context.Background())
if err != nil {
log.Fatalf("Failed to get extended card: %v", err)
}
fmt.Printf("Authenticated extended card: %v\n", agentCard.Name)
fmt.Printf("Authenticated extended card Desc: %v\n", agentCard.Description)
// Send the message
ctx, cancel := context.WithTimeout(context.Background(), config.Timeout)
defer cancel()
result, err := a2aClient.SendMessage(ctx, params)
if err != nil {
log.Fatalf("Failed to send message: %v", err)
}
// Handle the response based on its type
switch response := result.Result.(type) {
case *protocol.Message:
fmt.Printf("Message Response: %s\n", response.MessageID)
if response.ContextID != nil {
fmt.Printf("Context ID: %s\n", *response.ContextID)
}
// Print message parts
for _, part := range response.Parts {
if textPart, ok := part.(*protocol.TextPart); ok {
fmt.Printf("Response: %s\n", textPart.Text)
}
}
case *protocol.Task:
fmt.Printf("Task ID: %s, Status: %s\n", response.ID, response.Status.State)
if response.ContextID != "" {
fmt.Printf("Context ID: %s\n", response.ContextID)
}
// For demonstration purposes, get the task status
taskQuery := protocol.TaskQueryParams{
ID: response.ID,
}
updatedTask, err := a2aClient.GetTasks(ctx, taskQuery)
if err != nil {
log.Fatalf("Failed to get task: %v", err)
}
fmt.Printf("Updated task status: %s\n", updatedTask.Status.State)
default:
fmt.Printf("Unknown response type: %T\n", response)
}
}
// getJWTSecret retrieves the JWT secret from either the direct key or a file.
func getJWTSecret(config config) ([]byte, error) {
// If a secret file is provided, read from it
if config.JWTSecretFile != "" {
secret, err := os.ReadFile(config.JWTSecretFile)
if err != nil {
return nil, fmt.Errorf("failed to read JWT secret file: %w", err)
}
return secret, nil
}
// Otherwise use the direct secret value
return []byte(config.JWTSecret), nil
}
// createJWTClient creates an A2A client with JWT authentication.
func createJWTClient(config config) (*client.A2AClient, error) {
secret, err := getJWTSecret(config)
if err != nil {
return nil, err
}
return client.NewA2AClient(
config.AgentURL,
client.WithJWTAuth(secret, config.JWTAudience, config.JWTIssuer, config.JWTExpiry),
)
}
// createAPIKeyClient creates an A2A client with API key authentication.
func createAPIKeyClient(config config) (*client.A2AClient, error) {
return client.NewA2AClient(
config.AgentURL,
client.WithAPIKeyAuth(config.APIKey, config.APIKeyHeader),
)
}
// createOAuth2Client creates an A2A client with OAuth2 authentication.
func createOAuth2Client(config config) (*client.A2AClient, error) {
// Method 1: Using client credentials flow
return createOAuth2ClientCredentialsClient(config)
// Alternative methods:
// return createOAuth2TokenSourceClient(config)
// return createCustomOAuth2Client(config)
}
// createOAuth2ClientCredentialsClient creates a client using OAuth2 client credentials flow.
func createOAuth2ClientCredentialsClient(config config) (*client.A2AClient, error) {
// Determine token URL if not specified
tokenURL := config.OAuth2TokenURL
if tokenURL == "" {
tokenURL = getOAuthTokenURL(config.AgentURL)
}
// Parse scopes
scopes := []string{}
if config.OAuth2Scopes != "" {
for _, scope := range strings.Split(config.OAuth2Scopes, ",") {
scopes = append(scopes, strings.TrimSpace(scope))
}
}
return client.NewA2AClient(
config.AgentURL,
client.WithOAuth2ClientCredentials(config.OAuth2ClientID, config.OAuth2ClientSecret, tokenURL, scopes),
)
}
// createOAuth2TokenSourceClient creates a client using a custom OAuth2 token source.
func createOAuth2TokenSourceClient(config config) (*client.A2AClient, error) {
// Extract the OAuth token URL from agentURL
tokenURL := getOAuthTokenURL(config.AgentURL)
// Example with password credentials grant
config.OAuth2TokenURL = tokenURL
config.OAuth2Scopes = "a2a.read,a2a.write"
return createOAuth2ClientCredentialsClient(config)
}
// createCustomOAuth2Client creates a client with a completely custom OAuth2 provider.
func createCustomOAuth2Client(config config) (*client.A2AClient, error) {
// Extract the OAuth token URL from agentURL
tokenURL := getOAuthTokenURL(config.AgentURL)
// Create a client credentials config
ccConfig := &clientcredentials.Config{
ClientID: config.OAuth2ClientID,
ClientSecret: config.OAuth2ClientSecret,
TokenURL: tokenURL,
Scopes: []string{config.OAuth2Scopes},
}
// Create a custom OAuth2 provider
provider := auth.NewOAuth2ClientCredentialsProvider(
ccConfig.ClientID,
ccConfig.ClientSecret,
ccConfig.TokenURL,
ccConfig.Scopes,
)
// Use the custom provider
return client.NewA2AClient(
config.AgentURL,
client.WithAuthProvider(provider),
)
}
// getOAuthTokenURL is a helper function to get the OAuth token URL based on agent URL.
func getOAuthTokenURL(agentURL string) string {
tokenURL := ""
if agentURL == "http://localhost:8080/" {
tokenURL = "http://localhost:8080/oauth2/token"
} else {
// Try to adapt to a different port
// This is a simple adaptation, not fully robust
tokenURL = agentURL + "oauth2/token"
if tokenURL[len(tokenURL)-1] == '/' {
tokenURL = tokenURL[:len(tokenURL)-1]
}
}
fmt.Printf("Using OAuth2 token URL: %s\n", tokenURL)
return tokenURL
}