| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
package mcp |
| 6 |
|
| 7 |
import ( |
| 8 |
"context" |
| 9 |
"errors" |
| 10 |
"fmt" |
| 11 |
"iter" |
| 12 |
"log/slog" |
| 13 |
"slices" |
| 14 |
"strings" |
| 15 |
"sync" |
| 16 |
"sync/atomic" |
| 17 |
"time" |
| 18 |
|
| 19 |
"github.com/google/jsonschema-go/jsonschema" |
| 20 |
"github.com/modelcontextprotocol/go-sdk/internal/json" |
| 21 |
"github.com/modelcontextprotocol/go-sdk/internal/jsonrpc2" |
| 22 |
"github.com/modelcontextprotocol/go-sdk/jsonrpc" |
| 23 |
) |
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
type Client struct { |
| 28 |
impl *Implementation |
| 29 |
opts ClientOptions |
| 30 |
mu sync.Mutex |
| 31 |
roots *featureSet[*Root] |
| 32 |
sessions []*ClientSession |
| 33 |
sendingMethodHandler_ MethodHandler |
| 34 |
receivingMethodHandler_ MethodHandler |
| 35 |
} |
| 36 |
|
| 37 |
|
| 38 |
|
| 39 |
|
| 40 |
|
| 41 |
|
| 42 |
|
| 43 |
|
| 44 |
func NewClient(impl *Implementation, options *ClientOptions) *Client { |
| 45 |
if impl == nil { |
| 46 |
panic("nil Implementation") |
| 47 |
} |
| 48 |
var opts ClientOptions |
| 49 |
if options != nil { |
| 50 |
opts = *options |
| 51 |
} |
| 52 |
options = nil |
| 53 |
|
| 54 |
if opts.CreateMessageHandler != nil && opts.CreateMessageWithToolsHandler != nil { |
| 55 |
panic("cannot set both CreateMessageHandler and CreateMessageWithToolsHandler; use CreateMessageWithToolsHandler for tool support, or CreateMessageHandler for basic sampling") |
| 56 |
} |
| 57 |
if opts.Logger == nil { |
| 58 |
opts.Logger = ensureLogger(nil) |
| 59 |
} |
| 60 |
|
| 61 |
return &Client{ |
| 62 |
impl: impl, |
| 63 |
opts: opts, |
| 64 |
roots: newFeatureSet(func(r *Root) string { return r.URI }), |
| 65 |
sendingMethodHandler_: defaultSendingMethodHandler, |
| 66 |
receivingMethodHandler_: defaultReceivingMethodHandler[*ClientSession], |
| 67 |
} |
| 68 |
} |
| 69 |
|
| 70 |
|
| 71 |
type ClientOptions struct { |
| 72 |
|
| 73 |
Logger *slog.Logger |
| 74 |
|
| 75 |
|
| 76 |
|
| 77 |
|
| 78 |
|
| 79 |
|
| 80 |
|
| 81 |
CreateMessageHandler func(context.Context, *CreateMessageRequest) (*CreateMessageResult, error) |
| 82 |
|
| 83 |
|
| 84 |
|
| 85 |
|
| 86 |
|
| 87 |
|
| 88 |
|
| 89 |
|
| 90 |
|
| 91 |
|
| 92 |
|
| 93 |
|
| 94 |
CreateMessageWithToolsHandler func(context.Context, *CreateMessageWithToolsRequest) (*CreateMessageWithToolsResult, error) |
| 95 |
|
| 96 |
|
| 97 |
|
| 98 |
|
| 99 |
|
| 100 |
|
| 101 |
|
| 102 |
ElicitationHandler func(context.Context, *ElicitRequest) (*ElicitResult, error) |
| 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 |
Capabilities *ClientCapabilities |
| 148 |
|
| 149 |
ElicitationCompleteHandler func(context.Context, *ElicitationCompleteNotificationRequest) |
| 150 |
|
| 151 |
ToolListChangedHandler func(context.Context, *ToolListChangedRequest) |
| 152 |
PromptListChangedHandler func(context.Context, *PromptListChangedRequest) |
| 153 |
ResourceListChangedHandler func(context.Context, *ResourceListChangedRequest) |
| 154 |
ResourceUpdatedHandler func(context.Context, *ResourceUpdatedNotificationRequest) |
| 155 |
LoggingMessageHandler func(context.Context, *LoggingMessageRequest) |
| 156 |
ProgressNotificationHandler func(context.Context, *ProgressNotificationClientRequest) |
| 157 |
|
| 158 |
|
| 159 |
|
| 160 |
KeepAlive time.Duration |
| 161 |
} |
| 162 |
|
| 163 |
|
| 164 |
|
| 165 |
func (c *Client) bind(mcpConn Connection, conn *jsonrpc2.Connection, state *clientSessionState, onClose func()) *ClientSession { |
| 166 |
assert(mcpConn != nil && conn != nil, "nil connection") |
| 167 |
cs := &ClientSession{conn: conn, mcpConn: mcpConn, client: c, onClose: onClose} |
| 168 |
if state != nil { |
| 169 |
cs.state = *state |
| 170 |
} |
| 171 |
c.mu.Lock() |
| 172 |
defer c.mu.Unlock() |
| 173 |
c.sessions = append(c.sessions, cs) |
| 174 |
return cs |
| 175 |
} |
| 176 |
|
| 177 |
|
| 178 |
|
| 179 |
func (c *Client) disconnect(cs *ClientSession) { |
| 180 |
c.mu.Lock() |
| 181 |
defer c.mu.Unlock() |
| 182 |
c.sessions = slices.DeleteFunc(c.sessions, func(cs2 *ClientSession) bool { |
| 183 |
return cs2 == cs |
| 184 |
}) |
| 185 |
} |
| 186 |
|
| 187 |
|
| 188 |
type unsupportedProtocolVersionError struct { |
| 189 |
version string |
| 190 |
} |
| 191 |
|
| 192 |
func (e unsupportedProtocolVersionError) Error() string { |
| 193 |
return fmt.Sprintf("unsupported protocol version: %q", e.version) |
| 194 |
} |
| 195 |
|
| 196 |
|
| 197 |
type ClientSessionOptions struct { |
| 198 |
|
| 199 |
|
| 200 |
protocolVersion string |
| 201 |
} |
| 202 |
|
| 203 |
func (c *Client) capabilities(protocolVersion string) *ClientCapabilities { |
| 204 |
|
| 205 |
var caps *ClientCapabilities |
| 206 |
if c.opts.Capabilities != nil { |
| 207 |
|
| 208 |
caps = c.opts.Capabilities.clone() |
| 209 |
} else { |
| 210 |
|
| 211 |
|
| 212 |
caps = &ClientCapabilities{ |
| 213 |
RootsV2: &RootCapabilities{ |
| 214 |
ListChanged: true, |
| 215 |
}, |
| 216 |
} |
| 217 |
} |
| 218 |
|
| 219 |
|
| 220 |
if caps.RootsV2 != nil { |
| 221 |
caps.Roots = *caps.RootsV2 |
| 222 |
} |
| 223 |
|
| 224 |
|
| 225 |
if c.opts.CreateMessageHandler != nil || c.opts.CreateMessageWithToolsHandler != nil { |
| 226 |
if caps.Sampling == nil { |
| 227 |
caps.Sampling = &SamplingCapabilities{} |
| 228 |
if c.opts.CreateMessageWithToolsHandler != nil { |
| 229 |
caps.Sampling.Tools = &SamplingToolsCapabilities{} |
| 230 |
} |
| 231 |
} |
| 232 |
} |
| 233 |
|
| 234 |
|
| 235 |
if c.opts.ElicitationHandler != nil { |
| 236 |
if caps.Elicitation == nil { |
| 237 |
caps.Elicitation = &ElicitationCapabilities{} |
| 238 |
|
| 239 |
|
| 240 |
if protocolVersion >= protocolVersion20251125 { |
| 241 |
caps.Elicitation.Form = &FormElicitationCapabilities{} |
| 242 |
} |
| 243 |
} |
| 244 |
} |
| 245 |
return caps |
| 246 |
} |
| 247 |
|
| 248 |
|
| 249 |
|
| 250 |
|
| 251 |
|
| 252 |
|
| 253 |
|
| 254 |
|
| 255 |
func (c *Client) Connect(ctx context.Context, t Transport, opts *ClientSessionOptions) (cs *ClientSession, err error) { |
| 256 |
cs, err = connect(ctx, t, c, (*clientSessionState)(nil), nil, c.opts.Logger) |
| 257 |
if err != nil { |
| 258 |
return nil, err |
| 259 |
} |
| 260 |
|
| 261 |
protocolVersion := latestProtocolVersion |
| 262 |
if opts != nil && opts.protocolVersion != "" { |
| 263 |
protocolVersion = opts.protocolVersion |
| 264 |
} |
| 265 |
params := &InitializeParams{ |
| 266 |
ProtocolVersion: protocolVersion, |
| 267 |
ClientInfo: c.impl, |
| 268 |
Capabilities: c.capabilities(protocolVersion), |
| 269 |
} |
| 270 |
req := &InitializeRequest{Session: cs, Params: params} |
| 271 |
res, err := handleSend[*InitializeResult](ctx, methodInitialize, req) |
| 272 |
if err != nil { |
| 273 |
_ = cs.Close() |
| 274 |
return nil, err |
| 275 |
} |
| 276 |
if !slices.Contains(supportedProtocolVersions, res.ProtocolVersion) { |
| 277 |
return nil, unsupportedProtocolVersionError{res.ProtocolVersion} |
| 278 |
} |
| 279 |
cs.state.InitializeResult = res |
| 280 |
if hc, ok := cs.mcpConn.(clientConnection); ok { |
| 281 |
hc.sessionUpdated(cs.state) |
| 282 |
} |
| 283 |
req2 := &initializedClientRequest{Session: cs, Params: &InitializedParams{}} |
| 284 |
if err := handleNotify(ctx, notificationInitialized, req2); err != nil { |
| 285 |
_ = cs.Close() |
| 286 |
return nil, err |
| 287 |
} |
| 288 |
|
| 289 |
if c.opts.KeepAlive > 0 { |
| 290 |
cs.startKeepalive(c.opts.KeepAlive) |
| 291 |
} |
| 292 |
|
| 293 |
return cs, nil |
| 294 |
} |
| 295 |
|
| 296 |
|
| 297 |
|
| 298 |
|
| 299 |
|
| 300 |
|
| 301 |
|
| 302 |
type ClientSession struct { |
| 303 |
|
| 304 |
|
| 305 |
|
| 306 |
calledOnClose atomic.Bool |
| 307 |
onClose func() |
| 308 |
|
| 309 |
conn *jsonrpc2.Connection |
| 310 |
client *Client |
| 311 |
keepaliveCancel context.CancelFunc |
| 312 |
mcpConn Connection |
| 313 |
|
| 314 |
|
| 315 |
|
| 316 |
state clientSessionState |
| 317 |
|
| 318 |
|
| 319 |
pendingElicitationsMu sync.Mutex |
| 320 |
pendingElicitations map[string]chan struct{} |
| 321 |
} |
| 322 |
|
| 323 |
type clientSessionState struct { |
| 324 |
InitializeResult *InitializeResult |
| 325 |
} |
| 326 |
|
| 327 |
func (cs *ClientSession) InitializeResult() *InitializeResult { return cs.state.InitializeResult } |
| 328 |
|
| 329 |
func (cs *ClientSession) ID() string { |
| 330 |
if c, ok := cs.mcpConn.(hasSessionID); ok { |
| 331 |
return c.SessionID() |
| 332 |
} |
| 333 |
return "" |
| 334 |
} |
| 335 |
|
| 336 |
|
| 337 |
|
| 338 |
|
| 339 |
|
| 340 |
|
| 341 |
func (cs *ClientSession) Close() error { |
| 342 |
|
| 343 |
|
| 344 |
|
| 345 |
|
| 346 |
|
| 347 |
|
| 348 |
if cs.keepaliveCancel != nil { |
| 349 |
cs.keepaliveCancel() |
| 350 |
} |
| 351 |
err := cs.conn.Close() |
| 352 |
|
| 353 |
if cs.onClose != nil && cs.calledOnClose.CompareAndSwap(false, true) { |
| 354 |
cs.onClose() |
| 355 |
} |
| 356 |
|
| 357 |
return err |
| 358 |
} |
| 359 |
|
| 360 |
|
| 361 |
|
| 362 |
func (cs *ClientSession) Wait() error { |
| 363 |
return cs.conn.Wait() |
| 364 |
} |
| 365 |
|
| 366 |
|
| 367 |
|
| 368 |
|
| 369 |
|
| 370 |
|
| 371 |
|
| 372 |
|
| 373 |
|
| 374 |
|
| 375 |
func (cs *ClientSession) registerElicitationWaiter(elicitationID string) (await func(context.Context) error, cleanup func()) { |
| 376 |
|
| 377 |
ch := make(chan struct{}, 1) |
| 378 |
|
| 379 |
|
| 380 |
cs.pendingElicitationsMu.Lock() |
| 381 |
if cs.pendingElicitations == nil { |
| 382 |
cs.pendingElicitations = make(map[string]chan struct{}) |
| 383 |
} |
| 384 |
cs.pendingElicitations[elicitationID] = ch |
| 385 |
cs.pendingElicitationsMu.Unlock() |
| 386 |
|
| 387 |
|
| 388 |
await = func(ctx context.Context) error { |
| 389 |
select { |
| 390 |
case <-ctx.Done(): |
| 391 |
return fmt.Errorf("context cancelled while waiting for elicitation completion: %w", ctx.Err()) |
| 392 |
case <-ch: |
| 393 |
return nil |
| 394 |
} |
| 395 |
} |
| 396 |
|
| 397 |
cleanup = func() { |
| 398 |
cs.pendingElicitationsMu.Lock() |
| 399 |
delete(cs.pendingElicitations, elicitationID) |
| 400 |
cs.pendingElicitationsMu.Unlock() |
| 401 |
} |
| 402 |
|
| 403 |
return await, cleanup |
| 404 |
} |
| 405 |
|
| 406 |
|
| 407 |
func (cs *ClientSession) startKeepalive(interval time.Duration) { |
| 408 |
startKeepalive(cs, interval, &cs.keepaliveCancel, cs.client.opts.Logger) |
| 409 |
} |
| 410 |
|
| 411 |
|
| 412 |
|
| 413 |
|
| 414 |
func (c *Client) AddRoots(roots ...*Root) { |
| 415 |
|
| 416 |
if len(roots) == 0 { |
| 417 |
return |
| 418 |
} |
| 419 |
changeAndNotify(c, notificationRootsListChanged, &RootsListChangedParams{}, |
| 420 |
func() bool { c.roots.add(roots...); return true }) |
| 421 |
} |
| 422 |
|
| 423 |
|
| 424 |
|
| 425 |
|
| 426 |
func (c *Client) RemoveRoots(uris ...string) { |
| 427 |
changeAndNotify(c, notificationRootsListChanged, &RootsListChangedParams{}, |
| 428 |
func() bool { return c.roots.remove(uris...) }) |
| 429 |
} |
| 430 |
|
| 431 |
|
| 432 |
|
| 433 |
|
| 434 |
func changeAndNotify[P Params](c *Client, notification string, params P, change func() bool) { |
| 435 |
var sessions []*ClientSession |
| 436 |
|
| 437 |
c.mu.Lock() |
| 438 |
if change() { |
| 439 |
|
| 440 |
if c.shouldSendListChangedNotification(notification) { |
| 441 |
sessions = slices.Clone(c.sessions) |
| 442 |
} |
| 443 |
} |
| 444 |
c.mu.Unlock() |
| 445 |
notifySessions(sessions, notification, params, c.opts.Logger) |
| 446 |
} |
| 447 |
|
| 448 |
|
| 449 |
|
| 450 |
func (c *Client) shouldSendListChangedNotification(notification string) bool { |
| 451 |
|
| 452 |
caps := c.opts.Capabilities |
| 453 |
|
| 454 |
switch notification { |
| 455 |
case notificationRootsListChanged: |
| 456 |
|
| 457 |
if caps == nil { |
| 458 |
return true |
| 459 |
} |
| 460 |
|
| 461 |
if caps.RootsV2 != nil { |
| 462 |
return caps.RootsV2.ListChanged |
| 463 |
} |
| 464 |
return caps.Roots.ListChanged |
| 465 |
default: |
| 466 |
|
| 467 |
return true |
| 468 |
} |
| 469 |
} |
| 470 |
|
| 471 |
func (c *Client) listRoots(_ context.Context, req *ListRootsRequest) (*ListRootsResult, error) { |
| 472 |
c.mu.Lock() |
| 473 |
defer c.mu.Unlock() |
| 474 |
roots := slices.Collect(c.roots.all()) |
| 475 |
if roots == nil { |
| 476 |
roots = []*Root{} |
| 477 |
} |
| 478 |
return &ListRootsResult{ |
| 479 |
Roots: roots, |
| 480 |
}, nil |
| 481 |
} |
| 482 |
|
| 483 |
func (c *Client) createMessage(ctx context.Context, req *CreateMessageWithToolsRequest) (*CreateMessageWithToolsResult, error) { |
| 484 |
if c.opts.CreateMessageWithToolsHandler != nil { |
| 485 |
return c.opts.CreateMessageWithToolsHandler(ctx, req) |
| 486 |
} |
| 487 |
if c.opts.CreateMessageHandler != nil { |
| 488 |
|
| 489 |
baseParams, err := req.Params.toBase() |
| 490 |
if err != nil { |
| 491 |
return nil, err |
| 492 |
} |
| 493 |
baseReq := &CreateMessageRequest{ |
| 494 |
Session: req.Session, |
| 495 |
Params: baseParams, |
| 496 |
} |
| 497 |
res, err := c.opts.CreateMessageHandler(ctx, baseReq) |
| 498 |
if err != nil { |
| 499 |
return nil, err |
| 500 |
} |
| 501 |
return res.toWithTools(), nil |
| 502 |
} |
| 503 |
return nil, &jsonrpc.Error{Code: codeUnsupportedMethod, Message: "client does not support CreateMessage"} |
| 504 |
} |
| 505 |
|
| 506 |
|
| 507 |
|
| 508 |
|
| 509 |
|
| 510 |
|
| 511 |
|
| 512 |
|
| 513 |
|
| 514 |
|
| 515 |
|
| 516 |
|
| 517 |
func urlElicitationMiddleware() Middleware { |
| 518 |
return func(next MethodHandler) MethodHandler { |
| 519 |
return func(ctx context.Context, method string, req Request) (Result, error) { |
| 520 |
|
| 521 |
res, err := next(ctx, method, req) |
| 522 |
if err == nil { |
| 523 |
return res, nil |
| 524 |
} |
| 525 |
|
| 526 |
|
| 527 |
var rpcErr *jsonrpc.Error |
| 528 |
if !errors.As(err, &rpcErr) || rpcErr.Code != CodeURLElicitationRequired { |
| 529 |
return res, err |
| 530 |
} |
| 531 |
|
| 532 |
|
| 533 |
if strings.HasPrefix(method, "notifications/") { |
| 534 |
return res, err |
| 535 |
} |
| 536 |
|
| 537 |
|
| 538 |
cs, ok := req.GetSession().(*ClientSession) |
| 539 |
if !ok { |
| 540 |
return res, err |
| 541 |
} |
| 542 |
|
| 543 |
|
| 544 |
if cs.client.opts.ElicitationHandler == nil { |
| 545 |
return res, err |
| 546 |
} |
| 547 |
|
| 548 |
|
| 549 |
var errorData struct { |
| 550 |
Elicitations []*ElicitParams `json:"elicitations"` |
| 551 |
} |
| 552 |
if rpcErr.Data != nil { |
| 553 |
if err := json.Unmarshal(rpcErr.Data, &errorData); err != nil { |
| 554 |
return nil, fmt.Errorf("failed to parse URL elicitation error data: %w", err) |
| 555 |
} |
| 556 |
} |
| 557 |
|
| 558 |
|
| 559 |
for _, elicit := range errorData.Elicitations { |
| 560 |
mode := elicit.Mode |
| 561 |
if mode == "" { |
| 562 |
mode = "form" |
| 563 |
} |
| 564 |
if mode != "url" { |
| 565 |
return nil, fmt.Errorf("URLElicitationRequired error must only contain URL mode elicitations, got %q", mode) |
| 566 |
} |
| 567 |
} |
| 568 |
|
| 569 |
|
| 570 |
|
| 571 |
type waiter struct { |
| 572 |
await func(context.Context) error |
| 573 |
cleanup func() |
| 574 |
} |
| 575 |
waiters := make([]waiter, 0, len(errorData.Elicitations)) |
| 576 |
for _, elicitParams := range errorData.Elicitations { |
| 577 |
await, cleanup := cs.registerElicitationWaiter(elicitParams.ElicitationID) |
| 578 |
waiters = append(waiters, waiter{await: await, cleanup: cleanup}) |
| 579 |
} |
| 580 |
|
| 581 |
|
| 582 |
defer func() { |
| 583 |
for _, w := range waiters { |
| 584 |
w.cleanup() |
| 585 |
} |
| 586 |
}() |
| 587 |
|
| 588 |
|
| 589 |
for _, elicitParams := range errorData.Elicitations { |
| 590 |
elicitReq := newClientRequest(cs, elicitParams) |
| 591 |
_, elicitErr := cs.client.elicit(ctx, elicitReq) |
| 592 |
if elicitErr != nil { |
| 593 |
return nil, fmt.Errorf("URL elicitation failed: %w", elicitErr) |
| 594 |
} |
| 595 |
} |
| 596 |
|
| 597 |
|
| 598 |
for _, w := range waiters { |
| 599 |
if err := w.await(ctx); err != nil { |
| 600 |
return nil, err |
| 601 |
} |
| 602 |
} |
| 603 |
|
| 604 |
|
| 605 |
return next(ctx, method, req) |
| 606 |
} |
| 607 |
} |
| 608 |
} |
| 609 |
|
| 610 |
func (c *Client) elicit(ctx context.Context, req *ElicitRequest) (*ElicitResult, error) { |
| 611 |
if c.opts.ElicitationHandler == nil { |
| 612 |
return nil, &jsonrpc.Error{Code: jsonrpc.CodeInvalidParams, Message: "client does not support elicitation"} |
| 613 |
} |
| 614 |
|
| 615 |
|
| 616 |
mode := req.Params.Mode |
| 617 |
if mode == "" { |
| 618 |
mode = "form" |
| 619 |
} |
| 620 |
|
| 621 |
switch mode { |
| 622 |
case "form": |
| 623 |
if req.Params.URL != "" { |
| 624 |
return nil, &jsonrpc.Error{Code: jsonrpc.CodeInvalidParams, Message: "URL must not be set for form elicitation"} |
| 625 |
} |
| 626 |
schema, err := validateElicitSchema(req.Params.RequestedSchema) |
| 627 |
if err != nil { |
| 628 |
return nil, &jsonrpc.Error{Code: jsonrpc.CodeInvalidParams, Message: err.Error()} |
| 629 |
} |
| 630 |
res, err := c.opts.ElicitationHandler(ctx, req) |
| 631 |
if err != nil { |
| 632 |
return nil, err |
| 633 |
} |
| 634 |
|
| 635 |
if res.Action == "accept" && schema != nil && res.Content != nil { |
| 636 |
resolved, err := schema.Resolve(nil) |
| 637 |
if err != nil { |
| 638 |
return nil, &jsonrpc.Error{Code: jsonrpc.CodeInvalidParams, Message: fmt.Sprintf("failed to resolve requested schema: %v", err)} |
| 639 |
} |
| 640 |
if err := resolved.Validate(res.Content); err != nil { |
| 641 |
return nil, &jsonrpc.Error{Code: jsonrpc.CodeInvalidParams, Message: fmt.Sprintf("elicitation result content does not match requested schema: %v", err)} |
| 642 |
} |
| 643 |
err = resolved.ApplyDefaults(&res.Content) |
| 644 |
if err != nil { |
| 645 |
return nil, &jsonrpc.Error{Code: jsonrpc.CodeInvalidParams, Message: fmt.Sprintf("failed to apply schema defaults to elicitation result: %v", err)} |
| 646 |
} |
| 647 |
} |
| 648 |
return res, nil |
| 649 |
case "url": |
| 650 |
if req.Params.RequestedSchema != nil { |
| 651 |
return nil, &jsonrpc.Error{Code: jsonrpc.CodeInvalidParams, Message: "requestedSchema must not be set for URL elicitation"} |
| 652 |
} |
| 653 |
if req.Params.URL == "" { |
| 654 |
return nil, &jsonrpc.Error{Code: jsonrpc.CodeInvalidParams, Message: "URL must be set for URL elicitation"} |
| 655 |
} |
| 656 |
|
| 657 |
return c.opts.ElicitationHandler(ctx, req) |
| 658 |
default: |
| 659 |
return nil, &jsonrpc.Error{Code: jsonrpc.CodeInvalidParams, Message: fmt.Sprintf("unsupported elicitation mode: %q", mode)} |
| 660 |
} |
| 661 |
} |
| 662 |
|
| 663 |
|
| 664 |
|
| 665 |
func validateElicitSchema(wireSchema any) (*jsonschema.Schema, error) { |
| 666 |
if wireSchema == nil { |
| 667 |
return nil, nil |
| 668 |
} |
| 669 |
|
| 670 |
var schema *jsonschema.Schema |
| 671 |
if err := remarshal(wireSchema, &schema); err != nil { |
| 672 |
return nil, err |
| 673 |
} |
| 674 |
if schema == nil { |
| 675 |
return nil, nil |
| 676 |
} |
| 677 |
|
| 678 |
|
| 679 |
if schema.Type != "" && schema.Type != "object" { |
| 680 |
return nil, fmt.Errorf("elicit schema must be of type 'object', got %q", schema.Type) |
| 681 |
} |
| 682 |
|
| 683 |
|
| 684 |
if schema.Properties != nil { |
| 685 |
for propName, propSchema := range schema.Properties { |
| 686 |
if propSchema == nil { |
| 687 |
continue |
| 688 |
} |
| 689 |
|
| 690 |
if err := validateElicitProperty(propName, propSchema); err != nil { |
| 691 |
return nil, err |
| 692 |
} |
| 693 |
} |
| 694 |
} |
| 695 |
|
| 696 |
return schema, nil |
| 697 |
} |
| 698 |
|
| 699 |
|
| 700 |
func validateElicitProperty(propName string, propSchema *jsonschema.Schema) error { |
| 701 |
|
| 702 |
if len(propSchema.Properties) > 0 { |
| 703 |
return fmt.Errorf("elicit schema property %q contains nested properties, only primitive properties are allowed", propName) |
| 704 |
} |
| 705 |
|
| 706 |
switch propSchema.Type { |
| 707 |
case "string": |
| 708 |
return validateElicitStringProperty(propName, propSchema) |
| 709 |
case "number", "integer": |
| 710 |
return validateElicitNumberProperty(propName, propSchema) |
| 711 |
case "boolean": |
| 712 |
return validateElicitBooleanProperty(propName, propSchema) |
| 713 |
case "array": |
| 714 |
return validateElicitArrayProperty(propName, propSchema) |
| 715 |
default: |
| 716 |
return fmt.Errorf("elicit schema property %q has unsupported type %q, only string, number, integer, boolean, and array are allowed", propName, propSchema.Type) |
| 717 |
} |
| 718 |
} |
| 719 |
|
| 720 |
|
| 721 |
func validateElicitStringProperty(propName string, propSchema *jsonschema.Schema) error { |
| 722 |
|
| 723 |
if len(propSchema.Enum) > 0 { |
| 724 |
|
| 725 |
if propSchema.Type != "" && propSchema.Type != "string" { |
| 726 |
return fmt.Errorf("elicit schema property %q has enum values but type is %q, enums are only supported for string type", propName, propSchema.Type) |
| 727 |
} |
| 728 |
|
| 729 |
|
| 730 |
if propSchema.Extra != nil { |
| 731 |
if enumNamesRaw, exists := propSchema.Extra["enumNames"]; exists { |
| 732 |
|
| 733 |
if enumNamesSlice, ok := enumNamesRaw.([]any); ok { |
| 734 |
if len(enumNamesSlice) != len(propSchema.Enum) { |
| 735 |
return fmt.Errorf("elicit schema property %q has %d enum values but %d enumNames, they must match", propName, len(propSchema.Enum), len(enumNamesSlice)) |
| 736 |
} |
| 737 |
} else { |
| 738 |
return fmt.Errorf("elicit schema property %q has invalid enumNames type, must be an array", propName) |
| 739 |
} |
| 740 |
} |
| 741 |
} |
| 742 |
return nil |
| 743 |
} |
| 744 |
|
| 745 |
if propSchema.OneOf != nil { |
| 746 |
for _, entry := range propSchema.OneOf { |
| 747 |
if err := validateTitledEnumEntry(entry); err != nil { |
| 748 |
return fmt.Errorf("elicit schema property %q oneOf has invalid entry: %v", propName, err) |
| 749 |
} |
| 750 |
} |
| 751 |
return nil |
| 752 |
} |
| 753 |
|
| 754 |
|
| 755 |
if propSchema.Format != "" { |
| 756 |
allowedFormats := map[string]bool{ |
| 757 |
"email": true, |
| 758 |
"uri": true, |
| 759 |
"date": true, |
| 760 |
"date-time": true, |
| 761 |
} |
| 762 |
if !allowedFormats[propSchema.Format] { |
| 763 |
return fmt.Errorf("elicit schema property %q has unsupported format %q, only email, uri, date, and date-time are allowed", propName, propSchema.Format) |
| 764 |
} |
| 765 |
} |
| 766 |
|
| 767 |
|
| 768 |
if propSchema.MinLength != nil { |
| 769 |
if *propSchema.MinLength < 0 { |
| 770 |
return fmt.Errorf("elicit schema property %q has invalid minLength %d, must be non-negative", propName, *propSchema.MinLength) |
| 771 |
} |
| 772 |
} |
| 773 |
|
| 774 |
|
| 775 |
if propSchema.MaxLength != nil { |
| 776 |
if *propSchema.MaxLength < 0 { |
| 777 |
return fmt.Errorf("elicit schema property %q has invalid maxLength %d, must be non-negative", propName, *propSchema.MaxLength) |
| 778 |
} |
| 779 |
|
| 780 |
if propSchema.MinLength != nil && *propSchema.MaxLength < *propSchema.MinLength { |
| 781 |
return fmt.Errorf("elicit schema property %q has maxLength %d less than minLength %d", propName, *propSchema.MaxLength, *propSchema.MinLength) |
| 782 |
} |
| 783 |
} |
| 784 |
|
| 785 |
return validateDefaultProperty[string](propName, propSchema) |
| 786 |
} |
| 787 |
|
| 788 |
|
| 789 |
func validateElicitNumberProperty(propName string, propSchema *jsonschema.Schema) error { |
| 790 |
if propSchema.Minimum != nil && propSchema.Maximum != nil { |
| 791 |
if *propSchema.Maximum < *propSchema.Minimum { |
| 792 |
return fmt.Errorf("elicit schema property %q has maximum %g less than minimum %g", propName, *propSchema.Maximum, *propSchema.Minimum) |
| 793 |
} |
| 794 |
} |
| 795 |
|
| 796 |
intDefaultError := validateDefaultProperty[int](propName, propSchema) |
| 797 |
floatDefaultError := validateDefaultProperty[float64](propName, propSchema) |
| 798 |
if intDefaultError != nil && floatDefaultError != nil { |
| 799 |
return fmt.Errorf("elicit schema property %q has default value that cannot be interpreted as an int or float", propName) |
| 800 |
} |
| 801 |
|
| 802 |
return nil |
| 803 |
} |
| 804 |
|
| 805 |
|
| 806 |
func validateElicitArrayProperty(propName string, propSchema *jsonschema.Schema) error { |
| 807 |
if propSchema.Items == nil { |
| 808 |
return fmt.Errorf("elicit schema property %q is array but missing 'items' definition", propName) |
| 809 |
} |
| 810 |
|
| 811 |
items := propSchema.Items |
| 812 |
switch items.Type { |
| 813 |
case "string": |
| 814 |
|
| 815 |
if items.Enum == nil { |
| 816 |
return fmt.Errorf("elicit schema property %q items must specify enum for untitled enums", propName) |
| 817 |
} |
| 818 |
return nil |
| 819 |
case "": |
| 820 |
|
| 821 |
if len(items.AnyOf) == 0 { |
| 822 |
return fmt.Errorf("elicit schema property %q items must specify anyOf for titled enums", propName) |
| 823 |
} |
| 824 |
for _, entry := range items.AnyOf { |
| 825 |
if err := validateTitledEnumEntry(entry); err != nil { |
| 826 |
return fmt.Errorf("elicit schema property %q items has invalid entry: %v", propName, err) |
| 827 |
} |
| 828 |
} |
| 829 |
return nil |
| 830 |
default: |
| 831 |
return fmt.Errorf("elicit schema property %q items have unsupported type %q", propName, items.Type) |
| 832 |
} |
| 833 |
} |
| 834 |
|
| 835 |
func validateTitledEnumEntry(entry *jsonschema.Schema) error { |
| 836 |
if entry.Const == nil { |
| 837 |
return fmt.Errorf("const is required for titled enum entries") |
| 838 |
} |
| 839 |
constVal, ok := (*entry.Const).(string) |
| 840 |
if !ok { |
| 841 |
return fmt.Errorf("const must be a string for titled enum entries") |
| 842 |
} |
| 843 |
if constVal == "" { |
| 844 |
return fmt.Errorf("const cannot be empty for titled enum entries") |
| 845 |
} |
| 846 |
if entry.Title == "" { |
| 847 |
return fmt.Errorf("title is required for titled enum entries") |
| 848 |
} |
| 849 |
return nil |
| 850 |
} |
| 851 |
|
| 852 |
|
| 853 |
func validateElicitBooleanProperty(propName string, propSchema *jsonschema.Schema) error { |
| 854 |
return validateDefaultProperty[bool](propName, propSchema) |
| 855 |
} |
| 856 |
|
| 857 |
func validateDefaultProperty[T any](propName string, propSchema *jsonschema.Schema) error { |
| 858 |
|
| 859 |
if propSchema.Default != nil { |
| 860 |
var defaultValue T |
| 861 |
if err := json.Unmarshal(propSchema.Default, &defaultValue); err != nil { |
| 862 |
return fmt.Errorf("elicit schema property %q has invalid default value, must be a %T: %v", propName, defaultValue, err) |
| 863 |
} |
| 864 |
} |
| 865 |
return nil |
| 866 |
} |
| 867 |
|
| 868 |
|
| 869 |
|
| 870 |
|
| 871 |
|
| 872 |
|
| 873 |
|
| 874 |
|
| 875 |
|
| 876 |
|
| 877 |
func (c *Client) AddSendingMiddleware(middleware ...Middleware) { |
| 878 |
c.mu.Lock() |
| 879 |
defer c.mu.Unlock() |
| 880 |
addMiddleware(&c.sendingMethodHandler_, middleware) |
| 881 |
} |
| 882 |
|
| 883 |
|
| 884 |
|
| 885 |
|
| 886 |
|
| 887 |
|
| 888 |
|
| 889 |
|
| 890 |
|
| 891 |
|
| 892 |
func (c *Client) AddReceivingMiddleware(middleware ...Middleware) { |
| 893 |
c.mu.Lock() |
| 894 |
defer c.mu.Unlock() |
| 895 |
addMiddleware(&c.receivingMethodHandler_, middleware) |
| 896 |
} |
| 897 |
|
| 898 |
|
| 899 |
|
| 900 |
|
| 901 |
|
| 902 |
|
| 903 |
var clientMethodInfos = map[string]methodInfo{ |
| 904 |
methodComplete: newClientMethodInfo(clientSessionMethod((*ClientSession).Complete), 0), |
| 905 |
methodPing: newClientMethodInfo(clientSessionMethod((*ClientSession).ping), missingParamsOK), |
| 906 |
methodListRoots: newClientMethodInfo(clientMethod((*Client).listRoots), missingParamsOK), |
| 907 |
methodCreateMessage: newClientMethodInfo(clientMethod((*Client).createMessage), 0), |
| 908 |
methodElicit: newClientMethodInfo(clientMethod((*Client).elicit), missingParamsOK), |
| 909 |
notificationCancelled: newClientMethodInfo(clientSessionMethod((*ClientSession).cancel), notification|missingParamsOK), |
| 910 |
notificationToolListChanged: newClientMethodInfo(clientMethod((*Client).callToolChangedHandler), notification|missingParamsOK), |
| 911 |
notificationPromptListChanged: newClientMethodInfo(clientMethod((*Client).callPromptChangedHandler), notification|missingParamsOK), |
| 912 |
notificationResourceListChanged: newClientMethodInfo(clientMethod((*Client).callResourceChangedHandler), notification|missingParamsOK), |
| 913 |
notificationResourceUpdated: newClientMethodInfo(clientMethod((*Client).callResourceUpdatedHandler), notification|missingParamsOK), |
| 914 |
notificationLoggingMessage: newClientMethodInfo(clientMethod((*Client).callLoggingHandler), notification), |
| 915 |
notificationProgress: newClientMethodInfo(clientSessionMethod((*ClientSession).callProgressNotificationHandler), notification), |
| 916 |
notificationElicitationComplete: newClientMethodInfo(clientMethod((*Client).callElicitationCompleteHandler), notification|missingParamsOK), |
| 917 |
} |
| 918 |
|
| 919 |
func (cs *ClientSession) sendingMethodInfos() map[string]methodInfo { |
| 920 |
return serverMethodInfos |
| 921 |
} |
| 922 |
|
| 923 |
func (cs *ClientSession) receivingMethodInfos() map[string]methodInfo { |
| 924 |
return clientMethodInfos |
| 925 |
} |
| 926 |
|
| 927 |
func (cs *ClientSession) handle(ctx context.Context, req *jsonrpc.Request) (any, error) { |
| 928 |
if req.IsCall() { |
| 929 |
jsonrpc2.Async(ctx) |
| 930 |
} |
| 931 |
return handleReceive(ctx, cs, req) |
| 932 |
} |
| 933 |
|
| 934 |
func (cs *ClientSession) sendingMethodHandler() MethodHandler { |
| 935 |
cs.client.mu.Lock() |
| 936 |
defer cs.client.mu.Unlock() |
| 937 |
return cs.client.sendingMethodHandler_ |
| 938 |
} |
| 939 |
|
| 940 |
func (cs *ClientSession) receivingMethodHandler() MethodHandler { |
| 941 |
cs.client.mu.Lock() |
| 942 |
defer cs.client.mu.Unlock() |
| 943 |
return cs.client.receivingMethodHandler_ |
| 944 |
} |
| 945 |
|
| 946 |
|
| 947 |
func (cs *ClientSession) getConn() *jsonrpc2.Connection { return cs.conn } |
| 948 |
|
| 949 |
func (*ClientSession) ping(context.Context, *PingParams) (*emptyResult, error) { |
| 950 |
return &emptyResult{}, nil |
| 951 |
} |
| 952 |
|
| 953 |
|
| 954 |
|
| 955 |
|
| 956 |
|
| 957 |
|
| 958 |
func (*ClientSession) cancel(context.Context, *CancelledParams) (Result, error) { |
| 959 |
return nil, nil |
| 960 |
} |
| 961 |
|
| 962 |
func newClientRequest[P Params](cs *ClientSession, params P) *ClientRequest[P] { |
| 963 |
return &ClientRequest[P]{Session: cs, Params: params} |
| 964 |
} |
| 965 |
|
| 966 |
|
| 967 |
func (cs *ClientSession) Ping(ctx context.Context, params *PingParams) error { |
| 968 |
_, err := handleSend[*emptyResult](ctx, methodPing, newClientRequest(cs, orZero[Params](params))) |
| 969 |
return err |
| 970 |
} |
| 971 |
|
| 972 |
|
| 973 |
func (cs *ClientSession) ListPrompts(ctx context.Context, params *ListPromptsParams) (*ListPromptsResult, error) { |
| 974 |
return handleSend[*ListPromptsResult](ctx, methodListPrompts, newClientRequest(cs, orZero[Params](params))) |
| 975 |
} |
| 976 |
|
| 977 |
|
| 978 |
func (cs *ClientSession) GetPrompt(ctx context.Context, params *GetPromptParams) (*GetPromptResult, error) { |
| 979 |
return handleSend[*GetPromptResult](ctx, methodGetPrompt, newClientRequest(cs, orZero[Params](params))) |
| 980 |
} |
| 981 |
|
| 982 |
|
| 983 |
func (cs *ClientSession) ListTools(ctx context.Context, params *ListToolsParams) (*ListToolsResult, error) { |
| 984 |
return handleSend[*ListToolsResult](ctx, methodListTools, newClientRequest(cs, orZero[Params](params))) |
| 985 |
} |
| 986 |
|
| 987 |
|
| 988 |
|
| 989 |
|
| 990 |
func (cs *ClientSession) CallTool(ctx context.Context, params *CallToolParams) (*CallToolResult, error) { |
| 991 |
if params == nil { |
| 992 |
params = new(CallToolParams) |
| 993 |
} |
| 994 |
if params.Arguments == nil { |
| 995 |
|
| 996 |
params.Arguments = map[string]any{} |
| 997 |
} |
| 998 |
return handleSend[*CallToolResult](ctx, methodCallTool, newClientRequest(cs, orZero[Params](params))) |
| 999 |
} |
| 1000 |
|
| 1001 |
func (cs *ClientSession) SetLoggingLevel(ctx context.Context, params *SetLoggingLevelParams) error { |
| 1002 |
_, err := handleSend[*emptyResult](ctx, methodSetLevel, newClientRequest(cs, orZero[Params](params))) |
| 1003 |
return err |
| 1004 |
} |
| 1005 |
|
| 1006 |
|
| 1007 |
func (cs *ClientSession) ListResources(ctx context.Context, params *ListResourcesParams) (*ListResourcesResult, error) { |
| 1008 |
return handleSend[*ListResourcesResult](ctx, methodListResources, newClientRequest(cs, orZero[Params](params))) |
| 1009 |
} |
| 1010 |
|
| 1011 |
|
| 1012 |
func (cs *ClientSession) ListResourceTemplates(ctx context.Context, params *ListResourceTemplatesParams) (*ListResourceTemplatesResult, error) { |
| 1013 |
return handleSend[*ListResourceTemplatesResult](ctx, methodListResourceTemplates, newClientRequest(cs, orZero[Params](params))) |
| 1014 |
} |
| 1015 |
|
| 1016 |
|
| 1017 |
func (cs *ClientSession) ReadResource(ctx context.Context, params *ReadResourceParams) (*ReadResourceResult, error) { |
| 1018 |
return handleSend[*ReadResourceResult](ctx, methodReadResource, newClientRequest(cs, orZero[Params](params))) |
| 1019 |
} |
| 1020 |
|
| 1021 |
func (cs *ClientSession) Complete(ctx context.Context, params *CompleteParams) (*CompleteResult, error) { |
| 1022 |
return handleSend[*CompleteResult](ctx, methodComplete, newClientRequest(cs, orZero[Params](params))) |
| 1023 |
} |
| 1024 |
|
| 1025 |
|
| 1026 |
|
| 1027 |
func (cs *ClientSession) Subscribe(ctx context.Context, params *SubscribeParams) error { |
| 1028 |
_, err := handleSend[*emptyResult](ctx, methodSubscribe, newClientRequest(cs, orZero[Params](params))) |
| 1029 |
return err |
| 1030 |
} |
| 1031 |
|
| 1032 |
|
| 1033 |
|
| 1034 |
func (cs *ClientSession) Unsubscribe(ctx context.Context, params *UnsubscribeParams) error { |
| 1035 |
_, err := handleSend[*emptyResult](ctx, methodUnsubscribe, newClientRequest(cs, orZero[Params](params))) |
| 1036 |
return err |
| 1037 |
} |
| 1038 |
|
| 1039 |
func (c *Client) callToolChangedHandler(ctx context.Context, req *ToolListChangedRequest) (Result, error) { |
| 1040 |
if h := c.opts.ToolListChangedHandler; h != nil { |
| 1041 |
h(ctx, req) |
| 1042 |
} |
| 1043 |
return nil, nil |
| 1044 |
} |
| 1045 |
|
| 1046 |
func (c *Client) callPromptChangedHandler(ctx context.Context, req *PromptListChangedRequest) (Result, error) { |
| 1047 |
if h := c.opts.PromptListChangedHandler; h != nil { |
| 1048 |
h(ctx, req) |
| 1049 |
} |
| 1050 |
return nil, nil |
| 1051 |
} |
| 1052 |
|
| 1053 |
func (c *Client) callResourceChangedHandler(ctx context.Context, req *ResourceListChangedRequest) (Result, error) { |
| 1054 |
if h := c.opts.ResourceListChangedHandler; h != nil { |
| 1055 |
h(ctx, req) |
| 1056 |
} |
| 1057 |
return nil, nil |
| 1058 |
} |
| 1059 |
|
| 1060 |
func (c *Client) callResourceUpdatedHandler(ctx context.Context, req *ResourceUpdatedNotificationRequest) (Result, error) { |
| 1061 |
if h := c.opts.ResourceUpdatedHandler; h != nil { |
| 1062 |
h(ctx, req) |
| 1063 |
} |
| 1064 |
return nil, nil |
| 1065 |
} |
| 1066 |
|
| 1067 |
func (c *Client) callLoggingHandler(ctx context.Context, req *LoggingMessageRequest) (Result, error) { |
| 1068 |
if h := c.opts.LoggingMessageHandler; h != nil { |
| 1069 |
h(ctx, req) |
| 1070 |
} |
| 1071 |
return nil, nil |
| 1072 |
} |
| 1073 |
|
| 1074 |
func (cs *ClientSession) callProgressNotificationHandler(ctx context.Context, params *ProgressNotificationParams) (Result, error) { |
| 1075 |
if h := cs.client.opts.ProgressNotificationHandler; h != nil { |
| 1076 |
h(ctx, clientRequestFor(cs, params)) |
| 1077 |
} |
| 1078 |
return nil, nil |
| 1079 |
} |
| 1080 |
|
| 1081 |
func (c *Client) callElicitationCompleteHandler(ctx context.Context, req *ElicitationCompleteNotificationRequest) (Result, error) { |
| 1082 |
|
| 1083 |
if cs, ok := req.GetSession().(*ClientSession); ok { |
| 1084 |
cs.pendingElicitationsMu.Lock() |
| 1085 |
if ch, exists := cs.pendingElicitations[req.Params.ElicitationID]; exists { |
| 1086 |
select { |
| 1087 |
case ch <- struct{}{}: |
| 1088 |
default: |
| 1089 |
|
| 1090 |
} |
| 1091 |
} |
| 1092 |
cs.pendingElicitationsMu.Unlock() |
| 1093 |
} |
| 1094 |
|
| 1095 |
|
| 1096 |
if h := c.opts.ElicitationCompleteHandler; h != nil { |
| 1097 |
h(ctx, req) |
| 1098 |
} |
| 1099 |
return nil, nil |
| 1100 |
} |
| 1101 |
|
| 1102 |
|
| 1103 |
|
| 1104 |
|
| 1105 |
|
| 1106 |
func (cs *ClientSession) NotifyProgress(ctx context.Context, params *ProgressNotificationParams) error { |
| 1107 |
return handleNotify(ctx, notificationProgress, newClientRequest(cs, orZero[Params](params))) |
| 1108 |
} |
| 1109 |
|
| 1110 |
|
| 1111 |
|
| 1112 |
|
| 1113 |
|
| 1114 |
func (cs *ClientSession) Tools(ctx context.Context, params *ListToolsParams) iter.Seq2[*Tool, error] { |
| 1115 |
if params == nil { |
| 1116 |
params = &ListToolsParams{} |
| 1117 |
} |
| 1118 |
return paginate(ctx, params, cs.ListTools, func(res *ListToolsResult) []*Tool { |
| 1119 |
return res.Tools |
| 1120 |
}) |
| 1121 |
} |
| 1122 |
|
| 1123 |
|
| 1124 |
|
| 1125 |
|
| 1126 |
|
| 1127 |
func (cs *ClientSession) Resources(ctx context.Context, params *ListResourcesParams) iter.Seq2[*Resource, error] { |
| 1128 |
if params == nil { |
| 1129 |
params = &ListResourcesParams{} |
| 1130 |
} |
| 1131 |
return paginate(ctx, params, cs.ListResources, func(res *ListResourcesResult) []*Resource { |
| 1132 |
return res.Resources |
| 1133 |
}) |
| 1134 |
} |
| 1135 |
|
| 1136 |
|
| 1137 |
|
| 1138 |
|
| 1139 |
|
| 1140 |
func (cs *ClientSession) ResourceTemplates(ctx context.Context, params *ListResourceTemplatesParams) iter.Seq2[*ResourceTemplate, error] { |
| 1141 |
if params == nil { |
| 1142 |
params = &ListResourceTemplatesParams{} |
| 1143 |
} |
| 1144 |
return paginate(ctx, params, cs.ListResourceTemplates, func(res *ListResourceTemplatesResult) []*ResourceTemplate { |
| 1145 |
return res.ResourceTemplates |
| 1146 |
}) |
| 1147 |
} |
| 1148 |
|
| 1149 |
|
| 1150 |
|
| 1151 |
|
| 1152 |
|
| 1153 |
func (cs *ClientSession) Prompts(ctx context.Context, params *ListPromptsParams) iter.Seq2[*Prompt, error] { |
| 1154 |
if params == nil { |
| 1155 |
params = &ListPromptsParams{} |
| 1156 |
} |
| 1157 |
return paginate(ctx, params, cs.ListPrompts, func(res *ListPromptsResult) []*Prompt { |
| 1158 |
return res.Prompts |
| 1159 |
}) |
| 1160 |
} |
| 1161 |
|
| 1162 |
|
| 1163 |
func paginate[P listParams, R listResult[T], T any](ctx context.Context, params P, listFunc func(context.Context, P) (R, error), items func(R) []*T) iter.Seq2[*T, error] { |
| 1164 |
return func(yield func(*T, error) bool) { |
| 1165 |
for { |
| 1166 |
res, err := listFunc(ctx, params) |
| 1167 |
if err != nil { |
| 1168 |
yield(nil, err) |
| 1169 |
return |
| 1170 |
} |
| 1171 |
for _, r := range items(res) { |
| 1172 |
if !yield(r, nil) { |
| 1173 |
return |
| 1174 |
} |
| 1175 |
} |
| 1176 |
nextCursorVal := res.nextCursorPtr() |
| 1177 |
if nextCursorVal == nil || *nextCursorVal == "" { |
| 1178 |
return |
| 1179 |
} |
| 1180 |
*params.cursorPtr() = *nextCursorVal |
| 1181 |
} |
| 1182 |
} |
| 1183 |
} |