helpers

package
v1.33.1 Latest Latest
Warning

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

Go to latest
Published: Aug 21, 2026 License: MIT Imports: 19 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CountFromToolResult

func CountFromToolResult(result *mcp.CallToolResult) (int64, bool)

CountFromToolResult reads the count out of a NewCountToolResult result, for a tool wrapping a count_only call. Any other body reports false, so a wiring mistake surfaces instead of answering zero.

func CountOnlySchema

func CountOnlySchema(entity string) *jsonschema.Schema

CountOnlySchema returns the schema for the count_only flag of a list tool. entity is the plural noun the tool lists (e.g. "tasks").

func DateFilterSchema

func DateFilterSchema(description string) *jsonschema.Schema

DateFilterSchema returns the schema for an optional ISO 8601 date (YYYY-MM-DD) filter parameter. The caller supplies the purpose-specific description.

func DateTimeFilterSchema

func DateTimeFilterSchema(description string) *jsonschema.Schema

DateTimeFilterSchema returns the schema for an optional date-time filter parameter. The caller supplies the purpose-specific description.

Both accepted forms are spelled out with examples because a model asked about a date range emits a bare YYYY-MM-DD by default: a schema that advertises only format "date-time" costs a failed first call and a visible retry. The binders accept the plain date (see dateTimeLayouts), and the description says what it means so the caller is not left guessing whether the end of the range is included.

func FieldsSchema

func FieldsSchema[E any](entity string) *jsonschema.Schema

FieldsSchema returns the schema for the sparse-fieldset parameter of a list or get tool. E is the SDK entity struct the tool selects attributes of, the same one its OptionalFieldsParam validates against:

helpers.FieldsSchema[projects.Task]("task")

The accepted names are enumerated off E, so the enum cannot drift from the validator. The enum is the only place a model can read them: tool definitions carry no output schema, so without it the vocabulary is learnt one rejection at a time.

func HandleAPIError

func HandleAPIError(err error, label string) (*mcp.CallToolResult, error)

HandleAPIError processes an error returned from the Teamwork API and converts it into an appropriate MCP tool result or error.

Anything the API answered with — a status the caller can act on — becomes an error tool result, so the model reads the failure and can retry. Only an error with no status behind it (a transport failure, a decode fault) is returned as a Go error, which the SDK turns into a protocol-level error.

It reads the status from the v3 SDK's *twapi.HTTPError and, failing that, from the message text the Desk SDK produces. See deskStatusCodePattern.

func IntSliceToInt64

func IntSliceToInt64(slice []int) []int64

IntSliceToInt64 converts a slice of int to a slice of int64

func MatchAllTagsSchema

func MatchAllTagsSchema() *jsonschema.Schema

MatchAllTagsSchema returns the schema for the boolean flag that switches tag filtering between AND (true) and OR (false) semantics.

func NewCountToolResult

func NewCountToolResult[R twapi.HTTPRequester](
	ctx context.Context,
	engine *twapi.Engine,
	requester R,
	label string,
) (*mcp.CallToolResult, error)

NewCountToolResult answers a count_only request: it rewires requester to page 1, one row and an exact count, then returns {"count": N} from meta.page.count.

Pinning the exact count is correctness, not economy: skipCounts=true keeps `count` in the response but replaces the total with the lower bound (page * pageSize) + 1 — 2 for any non-empty result at pageSize=1. Four endpoints default to skipping, and the SDK's ResolveCount only clears the bound for callers decoding the typed response, which list tools do not.

func NewRawToolResult

func NewRawToolResult[R twapi.HTTPRequester](
	ctx context.Context,
	engine *twapi.Engine,
	requester R,
	label string,
	buildPath func(map[string]any) string,
) (*mcp.CallToolResult, error)

NewRawToolResult executes requester and returns the API response body verbatim, with web links injected, instead of decoding it into the SDK's typed response.

A `get_*` tool normally marshals that typed response, which is fine while it carries every attribute. It stops being fine under a sparse fieldset: the SDK structs do not use `omitempty`, so the attributes the caller excluded come back as zero values — `null`, `0`, `""` — which a caller cannot tell apart from real data. Streaming the body keeps them absent, which is what the selection asked for.

label is used for the error messages; buildPath is the WebLinker path builder for the entity.

func NewToolResultJSON

func NewToolResultJSON(v any) (*mcp.CallToolResult, error)

NewToolResultJSON creates a new JSON-based tool result.

func NewToolResultText

func NewToolResultText(format string, args ...any) *mcp.CallToolResult

NewToolResultText creates a new text-based tool result.

func NewToolResultTextError

func NewToolResultTextError(format string, args ...any) *mcp.CallToolResult

NewToolResultTextError creates a new MCP tool result representing an error with the given text message.

func NormalizeDateTime

func NormalizeDateTime(key, value string, endOfDay bool) (string, error)

NormalizeDateTime parses value with the same tolerance as the date-time parameter binders and re-renders it as RFC 3339, for handlers that forward the value to the API as a string instead of binding it to a time.Time. An empty value is returned unchanged. Set endOfDay for upper-bound filters, as described on EndOfDay.

func NotifySchema

func NotifySchema(description string, withFollowers bool) *jsonschema.Schema

NotifySchema returns the schema for a "notify" parameter. Every shape must be advertised here: the MCP SDK validates arguments against the schema before the handler runs, so parseNotify (twprojects) can only coerce what the schema allows. false = notify nobody. true = followers and the default when withFollowers (comments), otherwise an alias for "all", the default.

func NullifyEmptyDates added in v1.33.0

func NullifyEmptyDates(body []byte, fields ...string) []byte

NullifyEmptyDates rewrites an empty-string value held at any of the named JSON keys to null, wherever it appears in a raw API body.

The v1 routes spell "unset" as an empty string on a date field, and the list_* contract streams those bodies straight to the caller, so the SDK's MarshalJSON — which encodes an unset OptionalDateTime as null — never runs. WithDateTypeSchema declares such a field with a "date" or "date-time" format, and an empty string satisfies neither, so a client that asserts formats discards the whole response. Call this on any raw body carrying a field the published schema gives a date format.

Anything unexpected leaves the payload untouched: returning the response whole beats failing a read the API already answered.

func OrderBySchema

func OrderBySchema() *jsonschema.Schema

OrderBySchema returns the schema for an order-by parameter.

func OrderDirectionSchema

func OrderDirectionSchema() *jsonschema.Schema

OrderDirectionSchema returns the schema for an order-direction parameter accepting "asc" or "desc".

func PageOffsetSchema

func PageOffsetSchema() *jsonschema.Schema

PageOffsetSchema returns the schema for an offset-based pagination parameter (used by APIs that take a starting index rather than a page number).

func PageSchema

func PageSchema() *jsonschema.Schema

PageSchema returns the schema for a page-number pagination parameter.

func PageSizeSchema

func PageSizeSchema() *jsonschema.Schema

PageSizeSchema returns the schema for a page-size pagination parameter.

The bounds are the ones the v3 API enforces (https://apidocs.teamwork.com/guides/teamwork/how-does-paging-work): it rejects anything above 500 with a 400, so declaring the ceiling turns a wasted round trip into a client-side validation error.

func ParamGroup

func ParamGroup(params map[string]any, funcs ...ParamFunc) error

ParamGroup applies a series of functions to a map of parameters.

func RelationshipMetaID

func RelationshipMetaID(meta map[string]any, key string) (int64, bool)

RelationshipMetaID reads a numeric ID out of a relationship's meta bag.

The v3 API attaches hints to a relationship under "meta" — a task's tasklist relationship, for instance, carries the "projectId" the tasklist belongs to, which saves loading the tasklist just to resolve its project. The bag is decoded as map[string]any, so a JSON number arrives as float64; the other cases are covered for callers that decode with json.Number or receive the value as a string.

It reports false when the key is absent, holds a non-numeric value, or is not a positive ID, so callers can fall back to whatever they did before the hint existed.

func SearchTermSchema

func SearchTermSchema(entity, fields string) *jsonschema.Schema

SearchTermSchema returns the schema for a search-term filter parameter. fields describes what is searched (e.g. "name", "name or description").

func SliceToAny

func SliceToAny[T any](slice []T) []any

SliceToAny converts a slice of any type to []any for use with filter.In()

func SparseFieldNames

func SparseFieldNames[F ~string, E any]() []F

SparseFieldNames returns every attribute name the v3 sparse-fieldsets API accepts for the SDK entity struct E, typed as the entity's field alias F:

helpers.SparseFieldNames[projects.TaskField, projects.Task]()

The names are the entity's JSON attribute names, which is what both the SDK's generated `<Entity>Field` constants and the tool's generated output schema are built from — so the set is exactly the one a caller reads off that schema. Deriving them here rather than restating the SDK constants keeps the two in step across SDK upgrades that add or rename attributes.

func StructuredWebLinker

func StructuredWebLinker(
	ctx context.Context,
	data any,
	buildPath func(map[string]any) string,
	opts ...WebLinkerOption,
) any

StructuredWebLinker is a variant of WebLinker that operates on structured types. It marshals the data to JSON, applies WebLinker to inject web links, and unmarshals back to a generic representation. Because Go structs have fixed fields and cannot receive dynamically injected keys (like "meta.webLink"), the returned value is a map[string]any rather than the original typed struct.

Returns the original data unchanged if JSON marshaling fails, the customer URL is missing, or buildPath is nil.

func TagIDsAssociateSchema

func TagIDsAssociateSchema(entity string) *jsonschema.Schema

TagIDsAssociateSchema returns the schema for a tag-IDs list used to attach tags when creating or updating an entity.

func TagIDsFilterSchema

func TagIDsFilterSchema(entity string) *jsonschema.Schema

TagIDsFilterSchema returns the schema for a tag-IDs list used to filter listings by tag.

func UserGroupsSchema

func UserGroupsSchema(description string, required bool) *jsonschema.Schema

UserGroupsSchema returns the schema for a user/team/company/job-role groups parameter. The object accepts user_ids, company_ids, team_ids, and/or job_role_ids arrays; at least one (and at most all four) must be supplied with non-empty values. When required is true the returned schema is a bare object; when false it is wrapped in AnyOf with null so the caller can omit the field. The caller supplies the purpose-specific framing as description (pass "" when the helper is used as a branch of an outer schema that already carries a description).

func VerboseSchema

func VerboseSchema() *jsonschema.Schema

VerboseSchema returns the schema for a verbose flag controlling response detail level. When true (default), full entity details are returned; when false, sparse fieldsets are applied to reduce response size. Structured content is always returned; list-tool output schemas are relaxed (all fields optional) so sparse payloads still validate.

func WebLinker

func WebLinker(
	ctx context.Context,
	data []byte,
	buildPath func(map[string]any) string,
	opts ...WebLinkerOption,
) []byte

WebLinker processes JSON data to inject web links into entities based on their structure. It decodes the input data as JSON, traverses the top-level fields, and adds a "webLink" field in the meta section to qualifying objects using the provided buildPath function and customer URL from context.

The function handles two types of structures for each top-level field:

  • Single objects: {"field": {"id": 123, ...}} → adds webLink to the object
  • Arrays of objects: {"field": [{"id": 123, ...}, ...]} → adds webLink to each object in the array

Behavior:

  • Returns original data unchanged if JSON parsing fails, customer URL is missing, or buildPath is nil
  • Skips fields listed in the ignoreFields option (defaults to "meta" and "included")
  • Only processes objects within arrays; non-object array items are left unchanged
  • The webLink is constructed as: "{customerURL}/{path}" where path comes from buildPath()
  • If buildPath returns an empty string for an object, no webLink is added to that object

Parameters:

  • ctx: Context containing customer URL via twctx.CustomerURLFromContext
  • data: Raw JSON data as bytes
  • buildPath: Function that generates a path string from an object (e.g., "#users/123")
  • opts: Optional configuration (e.g., WebLinkerWithIgnoreFields to skip additional fields)

Returns the modified JSON data as bytes, or the original data if processing fails.

func WebLinkerWithIDPathBuilder

func WebLinkerWithIDPathBuilder(prefix string) func(map[string]any) string

WebLinkerWithIDPathBuilder creates a path builder function for entities with an "id" field. It returns a function that builds a path in the format "prefix/id" for objects containing a non-zero "id" field. Returns an empty string if the "id" field is missing or has a zero value.

func WithCountOnlySchema

func WithCountOnlySchema(schema *jsonschema.Schema) *jsonschema.Schema

WithCountOnlySchema declares the count_only body on a list tool's output schema, which otherwise describes rows only. Mutates in place and returns for chaining:

OutputSchema: helpers.WithCountOnlySchema(helpers.WithOptionalFields(taskListOutputSchema)),

func WithDateTypeSchema

func WithDateTypeSchema(opts *jsonschema.ForOptions) *jsonschema.ForOptions

WithDateTypeSchema registers JSON-schema overrides for the SDK's date types on the given generation options. Both twapi.Date and twapi.OptionalDateTime are defined over time.Time (`type Date time.Time`), so the reflection-based generator would otherwise emit a useless object schema for time.Time's unexported fields — while their MarshalJSON methods emit a string. Every response carrying one then fails output-schema validation on every call. The overrides force them to nullable strings matching what the marshaller actually writes.

The types are covered here rather than at each call site because a response picks them up transitively: projects.Team is the only model with an OptionalDateTime field, but SearchResponse sideloads Team, so the search schema needs the same override.

Use it whenever generating an output schema from a response type that carries (or sideloads) those fields:

schema, err = jsonschema.For[Response](helpers.WithDateTypeSchema(&jsonschema.ForOptions{}))

Any other options already set on opts (including pre-existing TypeSchemas entries) are preserved. The options value is modified in place and also returned for convenient chaining.

func WithMetaWebLinkSchema

func WithMetaWebLinkSchema(schema *jsonschema.Schema) *jsonschema.Schema

WithMetaWebLinkSchema patches a JSON schema generated from an API response type to include a meta.webLink property on entity objects. This aligns the output schema with the runtime behavior of WebLinker, which injects web links into serialized responses.

If the top-level schema is itself an array of objects, the "meta" property with a "webLink" field is added to each item schema.

Otherwise, the function walks the top-level properties of the schema and, for each property that is not a known root field (like "meta" or "included"):

  • If the property is an object, it adds a "meta" property with a "webLink" field to that object's schema.
  • If the property is an array of objects, it adds the "meta" property to the array item schema.

If the entity object already has a "meta" property in its schema, the "webLink" field is merged into the existing meta schema without overwriting any existing "webLink" definition.

The schema is modified in place and also returned for convenient chaining:

schema, err = jsonschema.For[Response](opts)
schema = helpers.WithMetaWebLinkSchema(schema)

func WithOptionalFields

func WithOptionalFields(schema *jsonschema.Schema) *jsonschema.Schema

WithOptionalFields recursively relaxes a schema and every nested schema it references (Properties, Items, AdditionalProperties, AnyOf/OneOf/AllOf branches) so it can validate sparse or forward-compatible payloads:

  • clears the `required` array, so sparse responses that omit fields still validate;
  • clears `additionalProperties` (reverting to the JSON Schema default of "allowed"), so fields the SDK response struct doesn't model — for example, new server-side fields — don't cause validation failures.

The schema is mutated in place and returned for convenient chaining at the call site:

OutputSchema: helpers.WithOptionalFields(xxxListOutputSchema),

Apply this only to list-tool schemas; single-entity `get_*` schemas should retain their strict `required` arrays so clients still receive useful constraints.

Types

type ParamFunc

type ParamFunc func(map[string]any) error

ParamFunc defines a function type that takes a map of parameters and returns an error. This is used to define functions that can retrieve parameters from a map, converting them to a specific type and applying middleware functions if necessary.

func OptionalCustomNumericListParam

func OptionalCustomNumericListParam[T interface{ Add(float64) }](
	target T,
	key string,
	middlewares ...ParamMiddleware[T],
) ParamFunc

OptionalCustomNumericListParam retrieves an optional list of numeric parameters from a map, converting each item to the specified numeric type using a custom type that implements the Add method. It returns an error if the key is not found or if the type conversion fails.

func OptionalDateParam

func OptionalDateParam(
	target *twapi.Date,
	key string,
	middlewares ...ParamMiddleware[string],
) ParamFunc

OptionalDateParam retrieves an optional date parameter from a map, converting it to a twapi.Date type. It returns an error if the type conversion fails. The date format is expected to be "YYYY-MM-DD". If the target is nil, it returns an error. If the key is not found, it does not set the target.

func OptionalDatePointerParam

func OptionalDatePointerParam(
	target **twapi.Date,
	key string,
	middlewares ...ParamMiddleware[string],
) ParamFunc

OptionalDatePointerParam retrieves an optional date parameter from a map and sets it to a pointer target. It converts the value to a twapi.Date type and applies middleware functions to the value before setting it. The date format is expected to be "YYYY-MM-DD". If the target is nil, it returns an error.

func OptionalFieldsParam

func OptionalFieldsParam[E any, F ~string](target *[]F, key string) ParamFunc

OptionalFieldsParam retrieves an optional sparse-fieldset parameter from a map and writes it into a `Filters.Fields.<Entity>` slot of a v3 list request. E is the SDK entity struct the slot selects attributes of (for example projects.Task for Filters.Fields.Tasks); F is inferred from target:

helpers.OptionalFieldsParam[projects.Task](&taskListRequest.Filters.Fields.Tasks, "fields")

Values are validated against the attributes E actually marshals to, and an unknown one fails the call with the valid names listed. The API ignores attributes it does not recognise, so without this a typo would come back as a response quietly missing a field the caller asked for — indistinguishable from the field being empty.

The entity id is always appended: it is what makes a row addressable by a follow-up get_* call, and WebLinker needs it to attach a web link.

An absent or empty value leaves target untouched, so callers can tell an explicit selection from none and keep their verbose default.

func OptionalLegacyDateParam

func OptionalLegacyDateParam(
	target *projects.LegacyDate,
	key string,
	middlewares ...ParamMiddleware[string],
) ParamFunc

OptionalLegacyDateParam retrieves an optional legacy date parameter from a map, converting it to a projects.LegacyDate type. It returns an error if the type conversion fails. The date format is expected to be "YYYYMMDD". If the target is nil, it returns an error. If the key is not found, it does not set the target.

func OptionalLegacyDatePointerParam

func OptionalLegacyDatePointerParam(
	target **projects.LegacyDate,
	key string,
	middlewares ...ParamMiddleware[string],
) ParamFunc

OptionalLegacyDatePointerParam retrieves an optional date parameter from a map and sets it to a pointer target. It converts the value to a projects.LegacyDate type and applies middleware functions to the value before setting it. The date format is expected to be "YYYYMMDD". If the target is nil, it returns an error.

func OptionalListParam

func OptionalListParam[T any](target *[]T, key string, middlewares ...ParamMiddleware[T]) ParamFunc

OptionalListParam retrieves an optional list parameter from a map, converting each item to the specified type. It returns an error if the key is not found or if the type conversion fails. If the target is nil, it returns an error.

func OptionalNumericListParam

func OptionalNumericListParam[T int8 | int16 | int32 | int64 |
	uint8 | uint16 | uint32 | uint64 |
	float32 | float64 |
	projects.LegacyNumber](
	target *[]T, key string, middlewares ...ParamMiddleware[T],
) ParamFunc

OptionalNumericListParam retrieves an optional list of numeric parameters from a map, converting each item to the specified numeric type. It returns an error if the key is not found or if the type conversion fails. If the target is nil, it returns an error.

func OptionalNumericParam

func OptionalNumericParam[T int8 | int16 | int32 | int64 |
	uint8 | uint16 | uint32 | uint64 |
	float32 | float64 |
	projects.LegacyNumber](
	target *T,
	key string,
	middlewares ...ParamMiddleware[T],
) ParamFunc

OptionalNumericParam retrieves an optional numeric parameter from a map, converting it to the target numeric type. It returns an error if the type conversion fails. If the target is nil, it returns an error.

func OptionalNumericPointerParam

func OptionalNumericPointerParam[T int8 | int16 | int32 | int64 |
	uint8 | uint16 | uint32 | uint64 |
	float32 | float64 |
	projects.LegacyNumber](
	target **T,
	key string,
	middlewares ...ParamMiddleware[T],
) ParamFunc

OptionalNumericPointerParam retrieves an optional numeric parameter from a map and sets it to a pointer target. It converts the value to the specified numeric type and applies middleware functions to the value before setting it. If the target is nil, it returns an error.

func OptionalParam

func OptionalParam[T any](target *T, key string, middlewares ...ParamMiddleware[T]) ParamFunc

OptionalParam retrieves an optional parameter from a map, converting it to the specified type. It returns an error if the type conversion fails. If the target is nil, it returns an error. It also allows for middleware functions to be applied to the value before setting it to the target. Each middleware function should return a boolean indicating whether to continue processing and an error if any issue occurs.

func OptionalPointerParam

func OptionalPointerParam[T any](target **T, key string, middlewares ...ParamMiddleware[T]) ParamFunc

OptionalPointerParam retrieves an optional parameter from a map and sets it to a pointer target. It converts the value to the specified type and applies middleware functions to the value before setting it. If the target is nil, it returns an error. The middleware functions should return a boolean indicating whether to continue processing and an error if any issue occurs. If the parameter is not found, it does not set the target pointer.

func OptionalTimeOnlyParam

func OptionalTimeOnlyParam(
	target *twapi.Time,
	key string,
	middlewares ...ParamMiddleware[string],
) ParamFunc

OptionalTimeOnlyParam retrieves an optional time parameter from a map, converting it to a twapi.Time type. It returns an error if the type conversion fails. If the target is nil, it returns an error.

func OptionalTimeOnlyPointerParam

func OptionalTimeOnlyPointerParam(
	target **twapi.Time,
	key string,
	middlewares ...ParamMiddleware[string],
) ParamFunc

OptionalTimeOnlyPointerParam retrieves an optional time parameter from a map and sets it to a pointer target. It converts the value to a twapi.Time type and applies middleware functions to the value before setting it. If the target is nil, it returns an error.

func OptionalTimeParam

func OptionalTimeParam(
	target *time.Time,
	key string,
	middlewares ...ParamMiddleware[string],
) ParamFunc

OptionalTimeParam retrieves an optional time parameter from a map, converting it to a time.Time type. It returns an error if the type conversion fails. If the target is nil, it returns an error. The accepted layouts are listed in dateTimeLayouts; pass EndOfDay for an upper-bound filter.

func OptionalTimePointerParam

func OptionalTimePointerParam(
	target **time.Time,
	key string,
	middlewares ...ParamMiddleware[string],
) ParamFunc

OptionalTimePointerParam retrieves an optional time parameter from a map and sets it to a pointer target. It converts the value to a time.Time type and applies middleware functions to the value before setting it. If the target is nil, it returns an error. The accepted layouts are listed in dateTimeLayouts; pass EndOfDay for an upper-bound filter.

func RequiredDateParam

func RequiredDateParam(
	target *twapi.Date,
	key string,
	middlewares ...ParamMiddleware[string],
) ParamFunc

RequiredDateParam retrieves a required date parameter from a map, converting it to a twapi.Date type. It returns an error if the key is not found or if the type conversion fails. The date format is expected to be "YYYY-MM-DD". If the target is nil, it returns an error.

func RequiredLegacyDateParam

func RequiredLegacyDateParam(
	target *projects.LegacyDate,
	key string,
	middlewares ...ParamMiddleware[string],
) ParamFunc

RequiredLegacyDateParam retrieves a required legacy date parameter from a map, converting it to a projects.LegacyDate type. It returns an error if the key is not found or if the type conversion fails. The date format is expected to be "YYYYMMDD". If the target is nil, it returns an error.

func RequiredNumericParam

func RequiredNumericParam[T int8 | int16 | int32 | int64 |
	uint8 | uint16 | uint32 | uint64 |
	float32 | float64 |
	projects.LegacyNumber](
	target *T,
	key string,
	middlewares ...ParamMiddleware[T],
) ParamFunc

RequiredNumericParam retrieves a required numeric parameter from a map, converting it to the target numeric type. It returns an error if the key is not found or if the type conversion fails. If the target is nil, it returns an error.

func RequiredParam

func RequiredParam[T any](target *T, key string, middlewares ...ParamMiddleware[T]) ParamFunc

RequiredParam retrieves a required parameter from a map, converting it to the specified type. It returns an error if the key is not found or if the type conversion fails. If the target is nil, it returns an error. It also allows for middleware functions to be applied to the value before setting it to the target. Each middleware function should return a boolean indicating whether to continue processing and an error if any issue occurs.

func RequiredTimeOnlyParam

func RequiredTimeOnlyParam(
	target *twapi.Time,
	key string,
	middlewares ...ParamMiddleware[string],
) ParamFunc

RequiredTimeOnlyParam retrieves a required time parameter from a map, converting it to a twapi.Time type. It returns an error if the key is not found or if the type conversion fails. If the target is nil, it returns an error.

func RequiredTimeParam

func RequiredTimeParam(
	target *time.Time,
	key string,
	middlewares ...ParamMiddleware[string],
) ParamFunc

RequiredTimeParam retrieves a required time parameter from a map, converting it to a time.Time type. It returns an error if the key is not found or if the type conversion fails. If the target is nil, it returns an error. The accepted layouts are listed in dateTimeLayouts; pass EndOfDay for an upper-bound filter.

type ParamMiddleware

type ParamMiddleware[T any] func(*T) (bool, error)

ParamMiddleware defines a function type that takes a pointer to a specific type and returns a boolean indicating whether to continue processing and an error if any issue occurs. This is used to apply middleware functions to parameters before they are set to the target.

func EndOfDay

func EndOfDay() ParamMiddleware[string]

EndOfDay marks a date-time parameter as an upper bound, so a date-only value resolves to the last second of the day the caller named rather than its first instant. Pass it to the time parameter binders for any filter that means "up to and including" — end_date, and the *_before window ends a model fills from a date range:

helpers.OptionalTimePointerParam(&req.Filters.EndDate, "end_date", helpers.EndOfDay())

Values that already carry a time of day are left untouched.

func RestrictValues

func RestrictValues[T comparable](allowedValues ...T) ParamMiddleware[T]

RestrictValues restricts the values of a parameter to a predefined set of allowed values. It can be used as a middleware function in the Param or OptionalParam functions.

type ToolArguments

type ToolArguments map[string]any

ToolArguments is a map of string keys to arbitrary values.

func NewToolArguments

func NewToolArguments(request *mcp.CallToolRequest) (ToolArguments, error)

NewToolArguments creates a ToolArguments instance from a CallToolRequest.

func (ToolArguments) GetBool

func (t ToolArguments) GetBool(key string, defaultValue bool) bool

GetBool returns a bool argument by key, or the default value if not found.

func (ToolArguments) GetBoolSlice

func (t ToolArguments) GetBoolSlice(key string, defaultValue []bool) []bool

GetBoolSlice returns a bool slice argument by key, or the default value if not found.

func (ToolArguments) GetFloat

func (t ToolArguments) GetFloat(key string, defaultValue float64) float64

GetFloat returns a float64 argument by key, or the default value if not found.

func (ToolArguments) GetFloatSlice

func (t ToolArguments) GetFloatSlice(key string, defaultValue []float64) []float64

GetFloatSlice returns a float64 slice argument by key, or the default value if not found.

func (ToolArguments) GetInt

func (t ToolArguments) GetInt(key string, defaultValue int) int

GetInt returns an int argument by key, or the default value if not found.

func (ToolArguments) GetIntSlice

func (t ToolArguments) GetIntSlice(key string, defaultValue []int) []int

GetIntSlice returns an int slice argument by key, or the default value if not found.

func (ToolArguments) GetString

func (t ToolArguments) GetString(key string, defaultValue string) string

GetString returns a string argument by key, or the default value if not found.

func (ToolArguments) GetStringSlice

func (t ToolArguments) GetStringSlice(key string, defaultValue []string) []string

GetStringSlice returns a string slice argument by key, or the default value if not found.

func (ToolArguments) RequireBool

func (t ToolArguments) RequireBool(key string) (bool, error)

RequireBool returns a bool argument by key, or an error if not found or not convertible to bool.

func (ToolArguments) RequireBoolSlice

func (t ToolArguments) RequireBoolSlice(key string) ([]bool, error)

RequireBoolSlice returns a bool slice argument by key, or an error if not found or not convertible to bool slice.

func (ToolArguments) RequireFloat

func (t ToolArguments) RequireFloat(key string) (float64, error)

RequireFloat returns a float64 argument by key, or an error if not found or not convertible to float64.

func (ToolArguments) RequireFloatSlice

func (t ToolArguments) RequireFloatSlice(key string) ([]float64, error)

RequireFloatSlice returns a float64 slice argument by key, or an error if not found or not convertible to float64 slice.

func (ToolArguments) RequireInt

func (t ToolArguments) RequireInt(key string) (int, error)

RequireInt returns an int argument by key, or an error if not found or not convertible to int.

func (ToolArguments) RequireIntSlice

func (t ToolArguments) RequireIntSlice(key string) ([]int, error)

RequireIntSlice returns an int slice argument by key, or an error if not found or not convertible to int slice.

func (ToolArguments) RequireString

func (t ToolArguments) RequireString(key string) (string, error)

RequireString returns a string argument by key, or an error if not found or not a string.

func (ToolArguments) RequireStringSlice

func (t ToolArguments) RequireStringSlice(key string) ([]string, error)

RequireStringSlice returns a string slice argument by key, or an error if not found or not convertible to string slice.

type WebLinkerOption

type WebLinkerOption func(*WebLinkerOptions)

WebLinkerOption is a function that configures the WebLinkerOptions.

func WebLinkerWithIgnoreFields

func WebLinkerWithIgnoreFields(fields ...string) WebLinkerOption

WebLinkerWithIgnoreFields creates an option to specify additional fields that should be ignored when processing JSON data for web link injection. These fields will be skipped in addition to the default knownRootFields ("meta" and "included").

type WebLinkerOptions

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

WebLinkerOptions holds configuration options for the WebLinker function.

Jump to

Keyboard shortcuts

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