qilin

package module
v0.1.0-beta.7 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 6, 2025 License: MIT Imports: 20 Imported by: 0

Documentation

Overview

Example
package main

import (
	"github.com/miyamo2/qilin"
)

type Req struct {
	X float64 `json:"x" jsonschema:"title=X"`
	Y float64 `json:"y" jsonschema:"title=Y"`
}

type Res struct {
	Result float64 `json:"result"`
}

func main() {
	q := qilin.New("calc")
	q.Tool("add", (*Req)(nil), func(c qilin.ToolContext) error {
		var req Req
		c.Bind(&req)
		res := Res{
			Result: req.X + req.Y,
		}
		return c.JSON(res)
	})
	q.Start() // listen and serve on stdio
}

Index

Examples

Constants

View Source
const (
	ProtocolVersion20250326 string = "2025-03-26"
	ProtocolVersion20241105 string = "2024-11-05"
	ProtocolVersion20241007 string = "2024-10-07"
	LatestProtocolVersion          = ProtocolVersion20250326
)
View Source
const (
	// MethodInitialize Initiates connection and negotiates protocol capabilities.
	// https://modelcontextprotocol.io/specification/2024-11-05/basic/lifecycle/#initialization
	MethodInitialize string = "initialize"

	// MethodPing Verifies connection liveness between client and server.
	// https://modelcontextprotocol.io/specification/2024-11-05/basic/utilities/ping/
	MethodPing string = "ping"

	// MethodResourcesList Lists all available server resources.
	// https://modelcontextprotocol.io/specification/2024-11-05/server/resources/
	MethodResourcesList string = "resources/list"

	// MethodResourcesTemplatesList Provides URI templates for constructing resource URIs.
	// https://modelcontextprotocol.io/specification/2024-11-05/server/resources/
	MethodResourcesTemplatesList string = "resources/templates/list"

	// MethodResourcesRead retrieves content of a specific resource by URI.
	// https://modelcontextprotocol.io/specification/2024-11-05/server/resources/
	MethodResourcesRead string = "resources/read"

	// MethodResourceSubscribe Subscribes to updates for a specific resource.
	// https://modelcontextprotocol.io/specification/2025-03-26/server/resources#subscriptions
	MethodResourceSubscribe string = "resources/subscribe"

	// MethodResourceUnsubscribe Unsubscribes from updates for a specific resource.
	// https://modelcontextprotocol.io/specification/2025-03-26/server/resources#subscriptions
	MethodResourceUnsubscribe string = "resources/unsubscribe"

	// MethodPromptsList lists all available prompt templates.
	// https://modelcontextprotocol.io/specification/2024-11-05/server/prompts/
	MethodPromptsList string = "prompts/list"

	// MethodPromptsGet Retrieves a specific prompt template with filled parameters.
	// https://modelcontextprotocol.io/specification/2024-11-05/server/prompts/
	MethodPromptsGet string = "prompts/get"

	// MethodToolsList Lists all available executable tools.
	// https://modelcontextprotocol.io/specification/2024-11-05/server/tools/
	MethodToolsList string = "tools/list"

	// MethodToolsCall Invokes a specific Tool with provided parameters.
	// https://modelcontextprotocol.io/specification/2024-11-05/server/tools/
	MethodToolsCall string = "tools/call"

	//
	MethodInitializedNotification = "notifications/initialized"

	// MethodNotificationResourcesListChanged Notifies when the list of available resources changes.
	// https://modelcontextprotocol.io/specification/2025-03-26/server/resources#list-changed-notification
	MethodNotificationResourcesListChanged = "notifications/resources/list_changed"

	// MethodNotificationResourceUpdated Notifies when a specific resource is updated.
	// https://modelcontextprotocol.io/specification/2025-03-26/server/resources#subscriptions
	MethodNotificationResourceUpdated = "notifications/resources/updated"

	// MethodCompletionComplete Completes a prompt template with provided parameters.
	MethodCompletionComplete = "completion/complete"

	MethodLoggingSetLevel = "logging/setLevel"
)
View Source
const (
	ErrorMessageFailedToHandleTool = "failed to handle Tool (name: %s): %w"
)
View Source
const JSONRPCVersion = "2.0"

JSONRPCVersion represents the version of the JSON-RPC protocol used in qilin.

Variables

View Source
var (
	// ErrAlreadySubscribed occurs when a subscription already exists
	ErrAlreadySubscribed = errors.New("already subscribed")
	// ErrResourceModificationSubscriptionNotFound occurs when a resource list subscription is not found
	ErrResourceModificationSubscriptionNotFound = errors.New("resource modification subscription not found")
	// ErrResourceListChangeSubscriptionNotFound occurs when a resource list subscription is not found
	ErrResourceListChangeSubscriptionNotFound = errors.New("resource list subscription not found")
)
View Source
var (
	ErrQilinLockingConflicts = errors.New("qilin is already running or there is a configuration process conflict")
)

Functions

func DefaultResourceListHandler

func DefaultResourceListHandler(c ResourceListContext) error

DefaultResourceListHandler is the default resource list handler.

Types

type Base64StringFunc

type Base64StringFunc func(data []byte) string

Base64StringFunc defines a function to encode binary data to a base64 string.

type BindableContext

type BindableContext interface {
	Context
	// Bind binds json data into the provided type `i`.
	Bind(i any) error
}

BindableContext is the context for handlers that able to bind JSON data

type CallToolContent

type CallToolContent interface {
	GetType() string
}

type CompletionsCapability

type CompletionsCapability struct{}

CompletionsCapability represents server capability for completions.

type Context

type Context interface {
	// Get retrieves data from the context.
	Get(key any) any
	// Set saves data in the context.
	Set(key any, val any)
	// JSONRPCRequest returns the JSONRPC request
	JSONRPCRequest() jsonrpc2.Request
	// Context returns the context
	Context() context.Context
	// SetContext sets the context
	SetContext(ctx context.Context)
}

type InMemoryResourceListChangeSubscriptionStore

type InMemoryResourceListChangeSubscriptionStore struct {
	// contains filtered or unexported fields
}

InMemoryResourceListChangeSubscriptionStore is an in-memory implementation of ResourceListChangeSubscriptionStore

NOTE: It will only work properly if Qilin is running on a single server.

func (*InMemoryResourceListChangeSubscriptionStore) Delete

func (*InMemoryResourceListChangeSubscriptionStore) Get

func (*InMemoryResourceListChangeSubscriptionStore) Issue

type InMemoryResourceModificationSubscriptionStore

type InMemoryResourceModificationSubscriptionStore struct {
	// contains filtered or unexported fields
}

InMemoryResourceModificationSubscriptionStore is an in-memory implementation of ResourceModificationSubscriptionStore

NOTE: It will only work properly if Qilin is running on a single server.

func (*InMemoryResourceModificationSubscriptionStore) Delete

func (*InMemoryResourceModificationSubscriptionStore) DeleteBySessionID

func (s *InMemoryResourceModificationSubscriptionStore) DeleteBySessionID(_ context.Context, sessionID string) error

func (*InMemoryResourceModificationSubscriptionStore) Get

func (*InMemoryResourceModificationSubscriptionStore) Issue

func (*InMemoryResourceModificationSubscriptionStore) RetrieveBySessionID

func (s *InMemoryResourceModificationSubscriptionStore) RetrieveBySessionID(_ context.Context, sessionID string) ([]Subscription, error)

func (*InMemoryResourceModificationSubscriptionStore) RetrieveUnhealthyURIBySessionID

func (s *InMemoryResourceModificationSubscriptionStore) RetrieveUnhealthyURIBySessionID(_ context.Context, sessionID string) ([]*url.URL, error)

type InMemorySessionStore

type InMemorySessionStore struct {
	// contains filtered or unexported fields
}

InMemorySessionStore is an in-memory implementation of SessionStore

NOTE: It will only work properly if Qilin is running on a single server.

func (*InMemorySessionStore) Context

func (s *InMemorySessionStore) Context(_ context.Context, sessionID string) (sessionCtx context.Context, err error)

func (*InMemorySessionStore) Delete

func (s *InMemorySessionStore) Delete(_ context.Context, sessionID string) (err error)

func (*InMemorySessionStore) Issue

func (s *InMemorySessionStore) Issue(_ context.Context) (sessionID string, err error)

type InMemorySubscription

type InMemorySubscription struct {
	// contains filtered or unexported fields
}

InMemorySubscription is an in-memory implementation of Subscription

NOTE: It will only work properly if Qilin is running on a single server.

func (*InMemorySubscription) LastAliveTime

func (s *InMemorySubscription) LastAliveTime() time.Time

LastAliveTime See: Subscription#LastAliveTime

func (*InMemorySubscription) SignalAlive

func (s *InMemorySubscription) SignalAlive()

SignalAlive See: Subscription#SignalAlive

func (*InMemorySubscription) Unsubscribed

func (s *InMemorySubscription) Unsubscribed() <-chan struct{}

Unsubscribed See: Subscription#Unsubscribed

type JSONMarshalFunc

type JSONMarshalFunc func(v any) ([]byte, error)

JSONMarshalFunc defines a function to marshal JSON data.

type JSONUnmarshalFunc

type JSONUnmarshalFunc func(data []byte, v any) error

JSONUnmarshalFunc defines a function to unmarshal JSON data.

type LoggingCapability

type LoggingCapability struct{}

LoggingCapability represents server capability for logging.

type NotificationsCancelledRequestParams

type NotificationsCancelledRequestParams struct {
	// RequestID is the ID of the request to cancel.
	// This MUST correspond to the ID of a request previously issued in the same direction.
	RequestID any `json:"requestId"`
	// Reason is an optional string describing the reason for the cancellation. This MAY be logged or presented to the user.
	Reason string `json:"reason"`
}

NotificationsCancelledRequestParams is sent by either side to indicate that it is cancelling a previously-issued request.

type Notify

type Notify func(ctx context.Context, method string, params interface{}) error

type NowFunc

type NowFunc func() time.Time

NowFunc defines a function to get the current time.

type Option

type Option func(*Qilin)

Option configures the Qilin instance.

func WithJSONMarshalFunc

func WithJSONMarshalFunc(f JSONMarshalFunc) Option

WithJSONMarshalFunc sets the JSON marshal function.

func WithJSONUnmarshalFunc

func WithJSONUnmarshalFunc(f JSONUnmarshalFunc) Option

WithJSONUnmarshalFunc sets the JSON unmarshal function.

func WithNowFunc

func WithNowFunc(f NowFunc) Option

WithNowFunc sets the function to get the current time.

func WithResourceListChangeSubscriptionHealthCheckInterval

func WithResourceListChangeSubscriptionHealthCheckInterval(interval time.Duration) Option

WithResourceListChangeSubscriptionHealthCheckInterval sets the health check interval for the resource list subscription.

func WithResourceSubscriptionHealthCheckInterval

func WithResourceSubscriptionHealthCheckInterval(interval time.Duration) Option

WithResourceSubscriptionHealthCheckInterval sets the health check interval for the resource subscription.

func WithResourcesListChangeSubscriptionStore

func WithResourcesListChangeSubscriptionStore(store ResourceListChangeSubscriptionStore) Option

WithResourcesListChangeSubscriptionStore sets the ResourceListChangeSubscriptionStore to the Qilin instance.

func WithResourcesSubscriptionStore

func WithResourcesSubscriptionStore(store ResourceModificationSubscriptionStore) Option

WithResourcesSubscriptionStore sets the ResourceModificationSubscriptionStore to the Qilin instance.

func WithSessionStore

func WithSessionStore(store SessionStore) Option

WithSessionStore sets the SessionStore to the Qilin instance.

func WithVersion

func WithVersion(version string) Option

type PromptCapability

type PromptCapability struct {
	// ListChanged indicates this server supports notifications for changes to the prompt list if true.
	ListChanged bool `json:"listChanged,omitzero"`
}

PromptCapability represents server capabilities for prompts.

type Qilin

type Qilin struct {
	// contains filtered or unexported fields
}

Qilin is the top-level framework instance.

func New

func New(name string, options ...Option) *Qilin

New creates a new Qilin instance.

func (*Qilin) Resource

func (q *Qilin) Resource(name, uri string, handler ResourceHandlerFunc, options ...ResourceOption)

Resource registers a new resource with the given name and description. If the URI contains path parameters, it will be registered as a template resource.

  • name: the name of the resource
  • uri: the URI of the resource
  • handler: the handler function for the resource
  • options: (optional) the options for the resource
Example
package main

import (
	"github.com/miyamo2/qilin"
)

type Employee struct {
	ID   string `json:"id" jsonschema:"title=ID"`
	Name string `json:"name" jsonschema:"title=Name"`
}

func main() {
	q := qilin.New("employee_management")
	q.Resource("get_employee", "example://example.com/{id}", func(c qilin.ResourceContext) error {
		c.Param("id")
		res := Employee{
			ID:   c.Param("id"),
			Name: "Bob",
		}
		return c.JSON(res)
	})
	q.Start() // listen and serve on stdio
}

func (*Qilin) ResourceChangeObserver

func (q *Qilin) ResourceChangeObserver(uri string, observer ResourceChangeObserverFunc)

ResourceChangeObserver registers a resource change observer for the given URI and runs the observer function.

func (*Qilin) ResourceList

func (q *Qilin) ResourceList(handler ResourceListHandlerFunc, middleware ...ResourceListMiddlewareFunc)

ResourceList registers a new resource list handler.

func (*Qilin) ResourceListChangeObserver

func (q *Qilin) ResourceListChangeObserver(observer ResourceListChangeObserverFunc)

ResourceListChangeObserver registers a resource list change observer and runs the observer function.

func (*Qilin) Start

func (q *Qilin) Start(options ...StartOption) error

Start starts Qilin app

func (*Qilin) Tool

func (q *Qilin) Tool(name string, req any, handler ToolHandlerFunc, options ...ToolOption)

Tool registers a new Tool with the given name and description.

  • name: the name of the Tool
  • req: the request schema for the Tool
  • handler: the handler function for the Tool
  • options: (optional) the options for the Tool
Example
package main

import (
	"github.com/miyamo2/qilin"
)

type Req struct {
	X float64 `json:"x" jsonschema:"title=X"`
	Y float64 `json:"y" jsonschema:"title=Y"`
}

type Res struct {
	Result float64 `json:"result"`
}

func main() {
	q := qilin.New("calc")
	q.Tool("add", (*Req)(nil), func(c qilin.ToolContext) error {
		var req Req
		c.Bind(&req)
		res := Res{
			Result: req.X + req.Y,
		}
		return c.JSON(res)
	})
	q.Start() // listen and serve on stdio
}

func (*Qilin) UseInResources

func (q *Qilin) UseInResources(middleware ...ResourceMiddlewareFunc)

UseInResources adds middleware to the resource handler chain.

func (*Qilin) UseInTools

func (q *Qilin) UseInTools(middleware ...ToolMiddlewareFunc)

UseInTools adds middleware to the Tool handler chain.

type Resource

type Resource struct {
	// URI of this resource.
	URI *ResourceURI `json:"uri"`

	// Name of the resource that is human-readable.
	//
	// This can be used by clients to populate UI elements.
	Name string `json:"name"`

	// Description of what this resource represents.
	//
	// This can be used by clients to improve the LLM's understanding of available resources.
	// It can be thought of like a "hint" to the model.
	Description string `json:"description,omitzero"`

	// MimeType of this resource, if known.
	MimeType string `json:"mimeType,omitzero"`
}

Resource that the server is capable of reading.

type ResourceCapability

type ResourceCapability struct {
	// Subscribe indicates this server supports subscribing to resource updates if true.
	Subscribe bool `json:"subscribe,omitzero"`

	// ListChanged indicates this server supports notifications for changes to the resource list if true.
	ListChanged bool `json:"listChanged,omitzero"`
}

ResourceCapability represents server capabilities for resources.

type ResourceChangeContext

type ResourceChangeContext interface {
	// Context returns the application scope context
	Context() context.Context

	// Publish publishes the resource change event
	Publish(uri *url.URL, modifiedAt time.Time)
	// contains filtered or unexported methods
}

ResourceChangeContext is the context for resource change publish handlers.

type ResourceChangeObserverFunc

type ResourceChangeObserverFunc func(c ResourceChangeContext)

ResourceChangeObserverFunc defines a function to handle resource change notifications.

The life cycle of this function must be in accordance with the application.

type ResourceChangeSubscriber

type ResourceChangeSubscriber interface {
	// ID returns the unique ID of the subscriber
	ID() string
	// SubscribedURI returns the subscribed resource URI
	SubscribedURI() *url.URL
	// LastReceived returns the last received time of the subscriber
	LastReceived() time.Time
	// Publish publishes the resource change event
	Publish(uri *url.URL)
}

ResourceChangeSubscriber is the interface for resource change subscribers

type ResourceContent

type ResourceContent interface {
	// GetURI returns the URI of the resource.
	GetURI() *url.URL
	// GetMimeType returns the MIME type of the resource.
	GetMimeType() string
	json.Marshaler
}

type ResourceContext

type ResourceContext interface {
	Context
	// ResourceURI returns the uri of the resource
	ResourceURI() *url.URL
	// MimeType returns the mime type of the resource
	MimeType() string
	// Param retrieves the path parameter by name
	Param(name string) string
	// String sends plain text content
	String(s string) error
	// JSON sends JSON content
	JSON(i any) error
	// Blob sends blob content
	//
	//  - data: the blob data
	//  - mimeType: (Optional) the mime type of the blob. if not provided, a resource mime type will be used.
	Blob(data []byte, mimeType string) error
}

ResourceContext is the context for resource handlers

type ResourceHandlerFunc

type ResourceHandlerFunc func(c ResourceContext) error

ResourceHandlerFunc defines a function to serve resource requests.

type ResourceListChangeContext

type ResourceListChangeContext interface {
	// Context returns the application scope context
	Context() context.Context
	// Publish publishes the resource list change event
	Publish(modifiedAt time.Time)
}

ResourceListChangeContext is the context for resource list change publish handlers

type ResourceListChangeObserverFunc

type ResourceListChangeObserverFunc func(c ResourceListChangeContext)

ResourceListChangeObserverFunc defines a function to handle resource list change notifications

The life cycle of this function must be in accordance with the application.

type ResourceListChangeSubscriber

type ResourceListChangeSubscriber interface {
	// ID returns the unique ID of the subscriber
	ID() string
	// LastReceived returns the last received time of the subscriber
	LastReceived() time.Time
	// Publish publishes the resource list change event
	Publish()
}

ResourceListChangeSubscriber sunscribe resource list changes

type ResourceListChangeSubscriptionManager

type ResourceListChangeSubscriptionManager interface {
	// SubscribeToResourceListChanges records that a resource list subscription has been started
	// and returns a Subscription.
	// if the subscription already exists, it returns the existing subscription.
	//
	//   ## params
	//
	//   - ctx: context
	//   - sessionID: identifier of the session
	//
	//   ## returns
	//
	//   - subscription: a subscription that can be used to check the health of the subscription
	//   - err: an error if the subscription failed
	SubscribeToResourceListChanges(
		ctx context.Context,
		sessionID string,
	) (subscription Subscription, err error)
	// UnsubscribeToResourceListChanges unsubscribes from the resource list changes
	//
	//   ## params
	//
	//   - ctx: context
	//   - sessionID: identifier of the session
	//
	//   ## returns
	//
	//   - err: an error if the unsubscription failed
	UnsubscribeToResourceListChanges(
		ctx context.Context,
		sessionID string,
	) error
	// Health returns true if the resource list subscription is healthy, otherwise false.
	//
	//   ## params
	//
	//   - ctx: context
	//   - sessionID: identifier of the session
	//
	//   ## returns
	//
	//   - healthy: true if the resource list subscription is healthy, otherwise false
	//   - err: an error if the health check failed
	Health(
		ctx context.Context,
		sessionID string,
	) (healthy bool, err error)
}

ResourceListChangeSubscriptionManager manages the subscription status of resource lists

type ResourceListChangeSubscriptionStore

type ResourceListChangeSubscriptionStore interface {
	// Get retrieves a subscription by session ID
	Get(ctx context.Context, sessionID string) (Subscription, error)
	// Issue issues a new subscription by session ID
	Issue(ctx context.Context, sessionID string) (Subscription, error)
	// Delete removes a subscription by session ID
	Delete(ctx context.Context, sessionID string) error
}

ResourceListChangeSubscriptionStore perpetuates resource list subscriptions

type ResourceListContext

type ResourceListContext interface {
	Context

	// Resources return registered resources.
	//
	// This includes templates, which must be replaced with the actual available paths in SetResource.
	Resources() map[string]Resource

	// SetResource sets the resource by uri
	//
	// must be the actual path and resource, not the template.
	SetResource(uri string, resource Resource)
}

ResourceListContext is the context for resource list handlers

type ResourceListHandlerFunc

type ResourceListHandlerFunc func(c ResourceListContext) error

ResourceListHandlerFunc defines a function to serve resource list requests.

type ResourceListMiddlewareFunc

type ResourceListMiddlewareFunc func(next ResourceListHandlerFunc) ResourceListHandlerFunc

ResourceListMiddlewareFunc defines a function to process resource list middleware.

type ResourceMiddlewareFunc

type ResourceMiddlewareFunc func(next ResourceHandlerFunc) ResourceHandlerFunc

ResourceMiddlewareFunc defines a function to process resource middleware.

type ResourceModificationSubscriptionStore

type ResourceModificationSubscriptionStore interface {
	// Get retrieves a subscription by session ID and URI
	Get(ctx context.Context, sessionID string, uri *url.URL) (Subscription, error)
	// Issue issues a new subscription by session ID and URI
	Issue(ctx context.Context, sessionID string, uri *url.URL) (Subscription, error)
	// Delete removes a subscription
	Delete(ctx context.Context, sessionID string, uri *url.URL) error
	// RetrieveBySessionID retrieves all subscriptions by session ID
	RetrieveBySessionID(ctx context.Context, sessionID string) ([]Subscription, error)
	// RetrieveUnhealthyURIBySessionID retrieves all unhealthy subscriptions uri by session ID
	RetrieveUnhealthyURIBySessionID(ctx context.Context, sessionID string) ([]*url.URL, error)
	// DeleteBySessionID deletes all subscriptions by session ID
	DeleteBySessionID(ctx context.Context, sessionID string) error
}

ResourceModificationSubscriptionStore perpetuates resource modification subscriptions

type ResourceOption

type ResourceOption func(*resourceOptions)

ResourceOption configures the resource options.

func ResourceWithDescription

func ResourceWithDescription(description string) ResourceOption

ResourceWithDescription configures the resource description.

Example
package main

import (
	"github.com/miyamo2/qilin"
)

type Employee struct {
	ID   string `json:"id" jsonschema:"title=ID"`
	Name string `json:"name" jsonschema:"title=Name"`
}

func main() {
	q := qilin.New("employee_management")
	q.Resource("get_employee", "example://example.com/{id}", func(c qilin.ResourceContext) error {
		c.Param("id")
		res := Employee{
			ID:   c.Param("id"),
			Name: "Bob",
		}
		return c.JSON(res)
	}, qilin.ResourceWithDescription("Get employee by ID"))
	q.Start() // listen and serve on stdio
}

func ResourceWithMiddleware

func ResourceWithMiddleware(middlewares ...ResourceMiddlewareFunc) ResourceOption

ResourceWithMiddleware configures the resource middleware.

func ResourceWithMimeType

func ResourceWithMimeType(mimeType string) ResourceOption

ResourceWithMimeType configures the resource MIME type.

Example
package main

import (
	"github.com/miyamo2/qilin"
)

type Employee struct {
	ID   string `json:"id" jsonschema:"title=ID"`
	Name string `json:"name" jsonschema:"title=Name"`
}

func main() {
	q := qilin.New("employee_management")
	q.Resource("get_employee", "example://example.com/{id}", func(c qilin.ResourceContext) error {
		c.Param("id")
		res := Employee{
			ID:   c.Param("id"),
			Name: "Bob",
		}
		return c.JSON(res)
	}, qilin.ResourceWithMimeType("application/json"))
	q.Start() // listen and serve on stdio
}

type ResourceURI

type ResourceURI url.URL

ResourceURI indicates a URI to a resource or sub-resource.

func (ResourceURI) MarshalJSON

func (r ResourceURI) MarshalJSON() ([]byte, error)

func (*ResourceURI) UnmarshalJSON

func (r *ResourceURI) UnmarshalJSON(bytes []byte) error

type ResourcesSubscriptionManager

type ResourcesSubscriptionManager interface {
	// SubscribeToResourceModification records that a resource modification subscription has been started
	// and returns a Subscription.
	// if the subscription already exists, it returns the existing subscription.
	//
	//   ## params
	//
	//   - ctx: context
	//   - sessionID: identifier of the session
	//   - resourceURI: the URI of the resource to subscribe to
	//
	//   ## returns
	//
	//   - subscription: a subscription that can be used to check the health of the subscription
	//   - err: an error if the subscription failed
	SubscribeToResourceModification(
		ctx context.Context,
		sessionID string,
		resourceURI *url.URL,
	) (Subscription, error)
	// UnsubscribeToResourceModification records that the resource modification subscription has been ended
	//
	//   ## params
	//
	//   - ctx: context
	//   - sessionID: identifier of the session
	//   - resourceURI: the URI of the resource to unsubscribe to
	//
	//   ## returns
	//
	//   - err: an error if the unsubscription failed
	UnsubscribeToResourceModification(
		ctx context.Context,
		sessionID string,
		resourceURI *url.URL,
	) error
	// UnhealthSubscriptions returns a list of unhealth subscriptions urls
	UnhealthSubscriptions(ctx context.Context, sessionID string) ([]*url.URL, error)
}

ResourcesSubscriptionManager manages the subscription status of resources

type RootsCapability

type RootsCapability struct {
	// ListChanged indicates whether the client supports notifications for changes to the roots list.
	ListChanged bool `json:"listChanged,omitzero"`
}

RootsCapability represents the client's capability to support roots features.

type ServerCapabilities

type ServerCapabilities struct {
	// Experimental contains non-standard capabilities that the server supports.
	Experimental map[string]any `json:"experimental,omitzero"`

	// Logging present if the server supports sending log messages to the client.
	Logging *LoggingCapability `json:"logging,omitzero"`

	// Completions present if the server supports argument autocompletion suggestions.
	Completions *CompletionsCapability `json:"completions,omitzero"`

	// Prompts present if the server offers any prompt templates.
	Prompts *PromptCapability `json:"prompts,omitzero"`

	// Resources present if the server offers any resources to read.
	Resources *ResourceCapability `json:"resources,omitzero"`

	// Tools present if the server offers any tools to call.
	Tools *ToolCapability `json:"tools,omitzero"`
}

ServerCapabilities is a set of capabilities defined here, but this is not a closed set: any server can define its own, additional capabilities.

type SessionManager

type SessionManager interface {
	// Start starts a session
	//
	//   ## params
	//
	//   - ctx: context
	//
	//   ## returns
	//
	//   - sessionID: the ID of the started session
	//   - err: an error if the session failed to start
	Start(ctx context.Context) (sessionID string, err error)

	// Context returns a session scoped context
	//
	//   ## params
	//
	//   - ctx: context
	//   - sessionID: session ID
	//
	//   ## returns
	//
	//   - ctx: a context that is scoped to the session
	//   - err: an error if failed to get the session context
	Context(ctx context.Context, sessionID string) (context.Context, error)

	// Discard discards a session
	Discard(ctx context.Context, sessionID string) error
}

SessionManager manages session

var DefaultSessionManager SessionManager = &sessionManager{
	store: &InMemorySessionStore{},
}

DefaultSessionManager default session manager

type SessionStore

type SessionStore interface {
	// Issue creates a new session and returns its ID.
	Issue(ctx context.Context) (sessionID string, err error)
	// Delete removes the session from the store.
	Delete(ctx context.Context, sessionID string) (err error)
	// Context returns the session-scoped context.
	Context(ctx context.Context, sessionID string) (sessionCtx context.Context, err error)
}

type StartOption

type StartOption func(*startOptions)

StartOption configures the startup settings for the Qilin instance

func StartWithContext

func StartWithContext(ctx context.Context) StartOption

StartWithContext settings the context

func StartWithFramer

func StartWithFramer(framer jsonrpc2.Framer) StartOption

StartWithFramer settings the jsonrpc2.Framer

func StartWithListener

func StartWithListener[T *transport.Stdio | *transport.Streamable](listener T) StartOption

StartWithListener settings the jsonrpc2.Listener

func StartWithPreempter

func StartWithPreempter(preempter jsonrpc2.Preempter) StartOption

StartWithPreempter settings the jsonrpc2.Preempter

type SubscribedResources

type SubscribedResources interface {
	Load(key any) (value any, ok bool)
	Store(key any, value any)
	Clear()
	LoadOrStore(key any, value any) (actual any, loaded bool)
	LoadAndDelete(key any) (value any, loaded bool)
	Delete(key any)
	Swap(key any, value any) (previous any, loaded bool)
	CompareAndSwap(key any, old any, new any) (swapped bool)
	CompareAndDelete(key any, old any) (deleted bool)
	Range(f func(key any, value any) bool)
}

SubscribedResources is a map of resources that the client is subscribed to.

key: <Qilin Client ID>#<Resource URI>

type Subscription

type Subscription interface {
	// SignalAlive signals that the subscription is still alive.
	SignalAlive()
	// Unsubscribed returns the channel that was closed when this subscription was canceled.
	Unsubscribed() <-chan struct{}
	// LastAliveTime returns the time when the subscription was last checked for health.
	LastAliveTime() time.Time
}

Subscription represents a subscription

type Tool

type Tool struct {
	// Name of the Tool.
	Name string `json:"name"`

	// Description of the Tool that is human-readable.
	Description string `json:"description,omitzero"`

	// InputSchema defines the arguments that the Tool accepts in JSON Schema format.
	InputSchema *jsonschema.Schema `json:"inputSchema"`

	// Annotations hint to the client about the Tool's behavior.
	Annotations *ToolAnnotations `json:"annotations,omitzero"`
	// contains filtered or unexported fields
}

Tool defines a Tool that the client can call.

type ToolAnnotations

type ToolAnnotations struct {
	// Title is a human-readable title for the Tool.
	Title string `json:"title,omitzero"`

	// ReadOnlyHint indicates the Tool does not modify its environment if true.
	ReadOnlyHint bool `json:"readOnlyHint,omitzero"`

	// DestructiveHint indicates whether the Tool may perform destructive updates to its environment if true.
	// If false, the Tool performs only additive updates.
	//
	// (This property is meaningful only when `readOnlyHint == false`)
	DestructiveHint bool `json:"destructiveHint,omitzero"`

	// IdempotentHint indicates that calling the Tool repeatedly with the same arguments
	// will have no additional effect on the its environment if true.
	//
	// (This property is meaningful only when `readOnlyHint == false`)
	IdempotentHint bool `json:"idempotentHint,omitzero"`

	// OpenWorldHint indicates this Tool may interact with an "open world" of external entities if true.
	// If false, the Tool's domain of interaction is closed.
	// For example, the world of a web search Tool is open, whereas that
	// of a memory Tool is not.
	OpenWorldHint bool `json:"openWorldHint,omitzero"`
}

ToolAnnotations represents additional properties describing a Tool to clients.

NOTE: all properties in ToolAnnotations are **hints**. They are not guaranteed to provide a faithful description of Tool behavior (including descriptive properties like `title`).

type ToolCapability

type ToolCapability struct {
	// ListChanged indicates this server supports notifications for changes to the Tool list if true.
	ListChanged bool `json:"listChanged,omitzero"`
}

ToolCapability represents server capabilities for tools.

type ToolContext

type ToolContext interface {
	BindableContext
	// ToolName returns the name of the Tool
	ToolName() string
	// Arguments return the arguments passed to the Tool
	Arguments() json.RawMessage
	// String sends plain text content
	String(s string) error
	// JSON sends JSON content
	JSON(i any) error
	// Image sends image content
	Image(data []byte, mimeType string) error
	// Audio sends audio content
	Audio(data []byte, mimeType string) error
	// JSONResource sends embed JSON resource content
	JSONResource(uri *url.URL, i any, mimeType string) error
	// StringResource sends embed string resource content
	StringResource(uri *url.URL, s string, mimeType string) error
	// BinaryResource sends embed binary resource content
	BinaryResource(uri *url.URL, data []byte, mimeType string) error
}

ToolContext is the context for Tool handlers

type ToolHandlerFunc

type ToolHandlerFunc func(c ToolContext) error

ToolHandlerFunc defines a function to serve Tool requests.

type ToolMiddlewareFunc

type ToolMiddlewareFunc func(next ToolHandlerFunc) ToolHandlerFunc

ToolMiddlewareFunc defines a function to process Tool middleware.

type ToolOption

type ToolOption func(*toolOptions)

ToolOption configures the Tool options.

func ToolWithAnnotations

func ToolWithAnnotations(annotations ToolAnnotations) ToolOption

ToolWithAnnotations configures the Tool annotations.

Example
package main

import (
	"github.com/miyamo2/qilin"
)

type Req struct {
	X float64 `json:"x" jsonschema:"title=X"`
	Y float64 `json:"y" jsonschema:"title=Y"`
}

type Res struct {
	Result float64 `json:"result"`
}

func main() {
	q := qilin.New("calc")
	q.Tool("add", (*Req)(nil), func(c qilin.ToolContext) error {
		var req Req
		c.Bind(&req)
		res := Res{
			Result: req.X + req.Y,
		}
		return c.JSON(res)
	}, qilin.ToolWithAnnotations(qilin.ToolAnnotations{
		Title:           "Calculation of x add y",
		ReadOnlyHint:    true,
		DestructiveHint: false,
		IdempotentHint:  false,
		OpenWorldHint:   false,
	}))
	q.Start() // listen and serve on stdio
}

func ToolWithDescription

func ToolWithDescription(description string) ToolOption

ToolWithDescription configures the Tool description.

Example
package main

import (
	"github.com/miyamo2/qilin"
)

type Req struct {
	X float64 `json:"x" jsonschema:"title=X"`
	Y float64 `json:"y" jsonschema:"title=Y"`
}

type Res struct {
	Result float64 `json:"result"`
}

func main() {
	q := qilin.New("calc")
	q.Tool("add", (*Req)(nil), func(c qilin.ToolContext) error {
		var req Req
		c.Bind(&req)
		res := Res{
			Result: req.X + req.Y,
		}
		return c.JSON(res)
	}, qilin.ToolWithDescription("add y to x"))
	q.Start() // listen and serve on stdio
}

func ToolWithMiddleware

func ToolWithMiddleware(middlewares ...ToolMiddlewareFunc) ToolOption

ToolWithMiddleware configures the Tool middleware.

Example
package main

import (
	"github.com/miyamo2/qilin"
)

type Req struct {
	X float64 `json:"x" jsonschema:"title=X"`
	Y float64 `json:"y" jsonschema:"title=Y"`
}

type Res struct {
	Result float64 `json:"result"`
}

func main() {
	q := qilin.New("calc")
	q.Tool("add", (*Req)(nil), func(c qilin.ToolContext) error {
		var req Req
		c.Bind(&req)
		res := Res{
			Result: req.X + req.Y,
		}
		return c.JSON(res)
	}, qilin.ToolWithMiddleware(func(next qilin.ToolHandlerFunc) qilin.ToolHandlerFunc {
		return func(c qilin.ToolContext) error {
			// do something before the handler
			return next(c)
		}
	}))
	q.Start() // listen and serve on stdio
}

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL