Debian Codegraph @

debian/go/src/github.com/modelcontextprotocol/go-sdk/internal/jsonrpc2/jsonrpc2.go

raw symbols SCIP
1 // Copyright 2018 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 jsonrpc2 is a minimal implementation of the JSON RPC 2 spec.
6 // https://www.jsonrpc.org/specification
7 // It is intended to be compatible with other implementations at the wire level.
8 package jsonrpc2
9
10 import (
11 "context"
12 "errors"
13 )
14
15 // ErrNotHandled is returned from a Handler or Preempter to indicate it did
16 // not handle the request.
17 //
18 // If a Handler returns ErrNotHandled, the server replies with
19 // ErrMethodNotFound.
20 var ErrNotHandled = errors.New("JSON RPC not handled")
21
22 // Preempter handles messages on a connection before they are queued to the main
23 // handler.
24 // Primarily this is used for cancel handlers or notifications for which out of
25 // order processing is not an issue.
26 type Preempter interface {
27 // Preempt is invoked for each incoming request before it is queued for handling.
28 //
29 // If Preempt returns ErrNotHandled, the request will be queued,
30 // and eventually passed to a Handle call.
31 //
32 // Otherwise, the result and error are processed as if returned by Handle.
33 //
34 // Preempt must not block. (The Context passed to it is for Values only.)
35 Preempt(ctx context.Context, req *Request) (result any, err error)
36 }
37
38 // Handler handles messages on a connection.
39 type Handler interface {
40 // Handle is invoked sequentially for each incoming request that has not
41 // already been handled by a Preempter.
42 //
43 // If the Request has a nil ID, Handle must return a nil result,
44 // and any error may be logged but will not be reported to the caller.
45 //
46 // If the Request has a non-nil ID, Handle must return either a
47 // non-nil, JSON-marshalable result, or a non-nil error.
48 //
49 // The Context passed to Handle will be canceled if the
50 // connection is broken or the request is canceled or completed.
51 // (If Handle returns ErrAsyncResponse, ctx will remain uncanceled
52 // until either Cancel or Respond is called for the request's ID.)
53 Handle(ctx context.Context, req *Request) (result any, err error)
54 }
55
56 // A HandlerFunc implements the Handler interface for a standalone Handle function.
57 type HandlerFunc func(ctx context.Context, req *Request) (any, error)
58
59 func (f HandlerFunc) Handle(ctx context.Context, req *Request) (any, error) {
60 return f(ctx, req)
61 }
62
63 var _ Handler = HandlerFunc(nil)