@protobase/server 0.58.2 → 0.58.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
- import { AssistantTool } from "./tools.js";
1
+ import { AssistantTool, ToolContext } from "./tools.js";
2
2
  import { WriteRecordToolsInput } from "./write-tool-limits.js";
3
3
  import "./write-record-tools.js";
4
4
  //#region src/assistant/batch-write-tool.d.ts
5
5
  /** Runs many writes in one transaction once the user approves them, under the caller's access rules. */
6
- export declare const batchWriteTool: (input?: WriteRecordToolsInput) => AssistantTool;
6
+ export declare const batchWriteTool: (input?: WriteRecordToolsInput) => AssistantTool<ToolContext>;
7
7
  //#endregion
@@ -1,4 +1,4 @@
1
- import { AssistantTool } from "./tools.js";
1
+ import { AssistantTool, ToolContext } from "./tools.js";
2
2
  import { WriteRecordToolsInput } from "./write-tool-limits.js";
3
3
  //#region src/assistant/comment-tools.d.ts
4
4
  /** The resources whose records take comments (`.comments()`), the only ones the comment tools reach. */
@@ -6,15 +6,15 @@ export type CommentToolsInput = {
6
6
  commented: string[];
7
7
  };
8
8
  /** Reads a page of a record's comments, newest first, under the caller's access rules. */
9
- export declare const listCommentsTool: (input: CommentToolsInput) => AssistantTool;
9
+ export declare const listCommentsTool: (input: CommentToolsInput) => AssistantTool<ToolContext>;
10
10
  /**
11
11
  * Adds the caller's comment to a record once the user approves it, under the caller's access rules. Given `resources`,
12
12
  * it comments only on those, and refuses any other before asking.
13
13
  */
14
- export declare const addCommentTool: (input: CommentToolsInput & WriteRecordToolsInput) => AssistantTool;
14
+ export declare const addCommentTool: (input: CommentToolsInput & WriteRecordToolsInput) => AssistantTool<ToolContext>;
15
15
  /**
16
16
  * `list_comments`, and `add_comment` when `writes` allows writing: on the resources with comments, and of those only
17
17
  * the ones `writes` lists when it lists some. None when no resource takes comments.
18
18
  */
19
- export declare const commentTools: ({ commented }: CommentToolsInput, writes: false | WriteRecordToolsInput) => AssistantTool[];
19
+ export declare const commentTools: ({ commented }: CommentToolsInput, writes: false | WriteRecordToolsInput) => AssistantTool<ToolContext>[];
20
20
  //#endregion
@@ -1,5 +1,5 @@
1
- import { AssistantTool } from "./tools.js";
1
+ import { AssistantTool, ToolContext } from "./tools.js";
2
2
  //#region src/assistant/count-records-tool.d.ts
3
3
  /** Counts a resource's records, in all or per value of a field, through the REST API's `count=exact` and `:aggregate`. */
4
- export declare const countRecordsTool: () => AssistantTool;
4
+ export declare const countRecordsTool: () => AssistantTool<ToolContext>;
5
5
  //#endregion
@@ -1,6 +1,6 @@
1
- import { AssistantTool } from "./tools.js";
1
+ import { AssistantTool, ToolContext } from "./tools.js";
2
2
  import { WriteRecordToolsInput } from "./write-tool-limits.js";
3
3
  //#region src/assistant/delete-record-tool.d.ts
4
4
  /** Deletes one record by its key and ETag once the user approves it, under the caller's access rules. */
5
- export declare const deleteRecordTool: (input?: WriteRecordToolsInput) => AssistantTool;
5
+ export declare const deleteRecordTool: (input?: WriteRecordToolsInput) => AssistantTool<ToolContext>;
6
6
  //#endregion
@@ -1,4 +1,4 @@
1
- import { AssistantTool } from "./tools.js";
1
+ import { AssistantTool, ToolContext } from "./tools.js";
2
2
  import { QueryOptions } from "./run-query.js";
3
3
  import { Db } from "@protobase/query";
4
4
  //#region src/assistant/query-tools.d.ts
@@ -7,10 +7,10 @@ import { Db } from "@protobase/query";
7
7
  * The rows show as a table in the chat. It runs as the query role, outside Protobase's access rules: it reads the
8
8
  * resources' tables only, never the auth schema.
9
9
  */
10
- export declare const readOnlyQueryTool: (db: Db, options?: QueryOptions) => AssistantTool;
10
+ export declare const readOnlyQueryTool: (db: Db, options?: QueryOptions) => AssistantTool<ToolContext>;
11
11
  /**
12
12
  * Lets the model change the app's database, never on its own: each call shows the statement on an approval card, and
13
13
  * only the user's Approve runs it, in a read-write transaction (see `runReadWriteQuery`). Reject, or no answer, runs nothing.
14
14
  */
15
- export declare const readWriteQueryTool: (db: Db, options?: QueryOptions) => AssistantTool;
15
+ export declare const readWriteQueryTool: (db: Db, options?: QueryOptions) => AssistantTool<ToolContext>;
16
16
  //#endregion
@@ -0,0 +1,10 @@
1
+ import "./records.js";
2
+ //#region src/assistant/record-tool-args.d.ts
3
+ /**
4
+ * A refusal the model can act on (no such resource, not allowed, a bad filter, a record a database constraint rejects)
5
+ * as `{ error, message }` JSON, as the REST API's problem words it; undefined for anything else.
6
+ */
7
+ export declare const refusalOf: (error: unknown) => string | undefined;
8
+ /** A refusal the model can act on is its to read, as `refusalOf` words it; anything else fails the call. */
9
+ export declare const refused: (error: unknown) => string;
10
+ //#endregion
@@ -2,15 +2,21 @@ import { problemOf } from "../error-handler.js";
2
2
  //#region src/assistant/record-tool-args.ts
3
3
  /**
4
4
  * A refusal the model can act on (no such resource, not allowed, a bad filter, a record a database constraint rejects)
5
- * is its to read, as the REST API's problem words it; anything else fails the call.
5
+ * as `{ error, message }` JSON, as the REST API's problem words it; undefined for anything else.
6
6
  */
7
- const refused = (error) => {
7
+ const refusalOf = (error) => {
8
8
  const problem = problemOf(error);
9
- if (problem && problem.status < 500) return JSON.stringify({
9
+ if (!problem || problem.status >= 500) return;
10
+ return JSON.stringify({
10
11
  error: problem.slug,
11
12
  message: problem.detail
12
13
  });
13
- throw error;
14
+ };
15
+ /** A refusal the model can act on is its to read, as `refusalOf` words it; anything else fails the call. */
16
+ const refused = (error) => {
17
+ const refusal = refusalOf(error);
18
+ if (refusal === void 0) throw error;
19
+ return refusal;
14
20
  };
15
21
  /** `show_deleted` as JSON `true` or `false`, absent being `false`; undefined for any other value, such as `"true"` or `1`. */
16
22
  const showDeletedOf = (args) => {
@@ -47,4 +53,4 @@ const showDeletedParameter = {
47
53
  description: "true also returns soft-deleted records; only on a resource list_resources marks soft_delete."
48
54
  };
49
55
  //#endregion
50
- export { invalidShowDeleted, keyOf, keyParameter, refused, resourceOf, resourceParameter, showDeletedOf, showDeletedParameter };
56
+ export { invalidShowDeleted, keyOf, keyParameter, refusalOf, refused, resourceOf, resourceParameter, showDeletedOf, showDeletedParameter };
@@ -1,16 +1,16 @@
1
- import { AssistantTool } from "./tools.js";
1
+ import { AssistantTool, ToolContext } from "./tools.js";
2
2
  //#region src/assistant/record-tools.d.ts
3
3
  /** Lists the resources the caller may read, small enough for a first call: names, labels and a line of help each, without fields. */
4
- export declare const listResourcesTool: () => AssistantTool;
4
+ export declare const listResourcesTool: () => AssistantTool<ToolContext>;
5
5
  /** Describes one resource the caller may read, with its fields, their labels, help and values, and which fields filters and sorts take. */
6
- export declare const describeResourceTool: () => AssistantTool;
6
+ export declare const describeResourceTool: () => AssistantTool<ToolContext>;
7
7
  /** Finds records of a resource with the REST API's filters, sorting and pages, under the caller's access rules. */
8
- export declare const listRecordsTool: () => AssistantTool;
8
+ export declare const listRecordsTool: () => AssistantTool<ToolContext>;
9
9
  /** Reads one record by its key, under the caller's access rules. */
10
- export declare const getRecordTool: () => AssistantTool;
10
+ export declare const getRecordTool: () => AssistantTool<ToolContext>;
11
11
  /**
12
12
  * `list_resources`, `describe_resource`, `list_records`, `count_records` and `get_record`: reading and counting the
13
13
  * app's records as the caller, through the REST API's rules.
14
14
  */
15
- export declare const readRecordTools: () => AssistantTool[];
15
+ export declare const readRecordTools: () => AssistantTool<ToolContext>[];
16
16
  //#endregion
@@ -1,7 +1,7 @@
1
1
  import { notFound } from "../problem.js";
2
2
  import { defineTool } from "./tools.js";
3
- import { listFields } from "./list-fields.js";
4
3
  import { invalidShowDeleted, keyOf, keyParameter, refused, resourceOf, resourceParameter, showDeletedOf, showDeletedParameter } from "./record-tool-args.js";
4
+ import { listFields } from "./list-fields.js";
5
5
  import { countRecordsTool } from "./count-records-tool.js";
6
6
  //#region src/assistant/record-tools.ts
7
7
  const readOnly = {
@@ -36,17 +36,24 @@ export type ToolAnnotations = {
36
36
  idempotentHint?: boolean;
37
37
  openWorldHint?: boolean;
38
38
  };
39
+ /** What every tool's context holds: a host's own MCP server, with no app records, gives its tools no more. */
40
+ export type BaseToolContext = Pick<ToolContext, 'session' | 'locale' | 'approve'>;
39
41
  /**
40
42
  * A function the model may call during a turn. `parameters` is the JSON Schema of its arguments; `run` gets them
41
43
  * parsed, checked against the schema over MCP but not in the dock, and returns what the model reads as the result.
44
+ * `run` gets a `ToolContext` unless the tool names a smaller one, such as `BaseToolContext` for a host's MCP server.
42
45
  */
43
- export type AssistantTool = {
46
+ export type AssistantTool<Context extends BaseToolContext = ToolContext> = {
44
47
  name: string;
45
48
  description: string;
46
49
  parameters: Record<string, unknown>;
47
- run: (args: Record<string, unknown>, context: ToolContext) => Promise<string>;
50
+ run: (args: Record<string, unknown>, context: Context) => Promise<string>;
48
51
  annotations?: ToolAnnotations;
52
+ /** MCP's display name for the tool, which `tools/list` gives as is; the dock ignores it. */
53
+ title?: string;
54
+ /** MCP's `_meta` for the tool, such as `securitySchemes`, which `tools/list` gives as is; the dock ignores it. */
55
+ _meta?: Record<string, unknown>;
49
56
  };
50
57
  /** Typed identity, for a tool of your own. */
51
- export declare const defineTool: (tool: AssistantTool) => AssistantTool;
58
+ export declare const defineTool: <Context extends BaseToolContext = ToolContext>(tool: AssistantTool<Context>) => AssistantTool<Context>;
52
59
  //#endregion
@@ -1,11 +1,11 @@
1
- import { AssistantTool } from "./tools.js";
1
+ import { AssistantTool, ToolContext } from "./tools.js";
2
2
  import { WriteRecordToolsInput } from "./write-tool-limits.js";
3
3
  //#region src/assistant/write-record-tools.d.ts
4
4
  /** Creates a record of a resource once the user approves it, under the caller's access rules. */
5
- export declare const createRecordTool: (input?: WriteRecordToolsInput) => AssistantTool;
5
+ export declare const createRecordTool: (input?: WriteRecordToolsInput) => AssistantTool<ToolContext>;
6
6
  /** Updates one record by its key once the user approves it, under the caller's access rules. */
7
- export declare const updateRecordTool: (input?: WriteRecordToolsInput) => AssistantTool;
7
+ export declare const updateRecordTool: (input?: WriteRecordToolsInput) => AssistantTool<ToolContext>;
8
8
  /** `create_record`, `update_record` and `delete_record`, on the resources `input` allows. */
9
- export declare const writeRecordTools: (input?: WriteRecordToolsInput) => AssistantTool[];
9
+ export declare const writeRecordTools: (input?: WriteRecordToolsInput) => AssistantTool<ToolContext>[];
10
10
  //#endregion
11
11
  export type { WriteRecordToolsInput };
package/dist/index.d.ts CHANGED
@@ -48,7 +48,7 @@ import { ToolComment, ToolCommentPage, ToolComments } from "./comments/tool-comm
48
48
  import { ConversationRecord, ConversationStore } from "./assistant/conversation-store.js";
49
49
  import { Conversation, ConversationsOptions, conversationKey, createConversations } from "./assistant/conversations.js";
50
50
  import { ApprovalAnswer, ApprovalRequest, requestApproval } from "./assistant/approval.js";
51
- import { AssistantTool, ReadableResources, ToolAnnotations, ToolContext, defineTool } from "./assistant/tools.js";
51
+ import { AssistantTool, BaseToolContext, ReadableResources, ToolAnnotations, ToolContext, defineTool } from "./assistant/tools.js";
52
52
  import { AssistantOptions, AssistantSettings, assistantRoles, assistantSettings, assistantVariables, seesAssistant } from "./assistant/assistant-settings.js";
53
53
  import { McpWrites } from "./mcp/mcp-writes.js";
54
54
  import { RuntimeOptions, runtimeUrl, runtimeVariable, seesRuntime } from "./runtime/runtime-settings.js";
@@ -118,6 +118,7 @@ import { AssistantBackend, assistantProtocolRoutes } from "./assistant/protocol-
118
118
  import { fileConversationStore } from "./assistant/file-conversation-store.js";
119
119
  import { withCacheBreakpoints } from "./assistant/cache-breakpoints.js";
120
120
  import { TurnOptions, runTurn } from "./assistant/turn.js";
121
+ import { refusalOf, refused } from "./assistant/record-tool-args.js";
121
122
  import { readableResources } from "./assistant/readable-resources.js";
122
123
  import { WidgetOptions, maxWidgetPropsBytes, widget } from "./assistant/widget.js";
123
124
  import { QueryOptions, QueryResult, runReadOnlyQuery, runReadWriteQuery } from "./assistant/run-query.js";
@@ -170,4 +171,4 @@ import { DrainResult, JobsRuntime, StartJobsOptions, startJobs } from "./jobs/ru
170
171
  import { jobsDrainApp } from "./jobs/drain-route.js";
171
172
  import { checkJobsSchema, jobsSchema, jobsSchemaMigration } from "./jobs/schema.js";
172
173
  import { AdminAuth, CreateAuthOptions, UserCreatedHook, normalizeRoles } from "./better-auth/create-auth.js";
173
- export { type Admin, type AdminAuth, type AdminOptions, type AggregateParams, type ApiFunction, type ApiKeys, type ApiKeysOptions, type ApnsEnvironment, type AppIcons, type AppIdentity, type AppPoolConfig, type ApplyOptions, type ApplyResult, type ApprovalAnswer, type ApprovalRequest, type ArgumentsPayload, type AssistantBackend, type AssistantOptions, type AssistantSettings, type AssistantTool, type AuditEvent, type AuditQueue, type AuthHooks, type AuthSettings, type AuthenticateSettings, type Authenticator, type BatchOperation, type BatchResult, type BetterAuthAuthenticator, type BetterAuthAuthenticatorOptions, type Caller, type CallerOptions, type CapturedRow, type CascadingKey, type ChatMessage, type ChatTextPart, type CheckAiInput, type CleanupEntry, type CleanupReport, type CleanupSchedule, type CoalescedChange, type CommentItem, type CommentToolsInput, type CommentUsers, type Completion, type CompletionOptions, ConnectionsBusy, type Conversation, type ConversationRecord, type ConversationStore, type ConversationsOptions, type CorsOptions, type CorsOrigins, type CreateAdminInput, type CreateAuthOptions, type DecryptField, type Device, type DeviceColumn, type DeviceKind, type DeviceStore, DeviceStoreError, type DrainResult, type EmailComponent, type EmailOptions, type EmailTemplate, type EncryptionStatus, type EncryptionTools, type EncryptionToolsInput, type EnqueueJob, type EnqueueOptions, type ErrorReporter, type ErrorReportingOptions, type ErrorReportingSettings, type EventData, type EventsOptions, FatalJobError, type FieldApplied, type FieldDecrypter, type FieldReader, type FieldStatus, type FileCleanupInput, type FileLimits, type FileObject, type FileProvider, type FileProviderSettings, type FileRef, type FileStore, type FileVariantObject, type FilesOptions, type FunctionApp, type FunctionCaller, type FunctionContext, type FunctionEnv, type FunctionHandler, type FunctionOptions, type FunctionRecords, type FunctionSocket, type FunctionSource, type HistoryColumn, type HistoryOptions, type HistoryPosition, type HistoryStore, HistoryStoreError, type HookContext, HttpProblem, type IssueTokenOptions, type JobContext, type JobDeclaration, type JobDefinition, type JobName, type JobOptions, type JobPayload, type JobRun, type JobsRuntime, type JsonObject, type JsonValue, type JwtOptions, type JwtVerifyOptions, type KeyFunctionContext, type LinkedAccount, type ListParams, type LocalFilesOptions, type MailMessage, type Mailer, type MapLayer, type MapOptions, type MapSettings, type McpApprovals, type McpGateInput, type McpHandlerInput, type McpRoutesInput, type McpServerInput, type McpToolsInput, type McpWrites, type MemberInput, type Membership, MissingCredentials, type MobileConfig, ModelError, type ModelSettings, type NewDevice, type NewNotification, type NewOrganization, type NewUser, type NotificationRecipients, NotificationSendError, type NotificationsOptions, type OperatorProvider, type OrganizationRole, type OrganizationsOptions, type PgModule, type PipelineHook, type PlatformSignIn, type PluginOption, type PluginRef, type PngIcon, type ProtectedFunctionOptions, type PublicFunctionContext, type PublicFunctionEnv, type PublicFunctionHandler, type PublicFunctionOptions, type PushAnswer, type PushMessage, PushMessageError, type PushSender, type QueryOptions, type QueryResult, type ReadableResources, type RealtimeOptions, type RealtimePrune, type ReasoningDetail, type ReasoningEffort, type RebindOption, type RecordGroups, type RecordKey, type RecordKeyInput, type RecordPage, type RenderedEmail, type ResourceChange, type ResourceSource, type RoleDefinition, type RolesInput, type RunContext, type RuntimeOptions, type S3Bucket, type S3FilesOptions, type S3ListPage, type S3Object, type ScanGuardMode, type ScheduledDelete, type SendNotification, type Session, type SessionOrganization, type Sharp, type SignInPolicy, type SignInRule, type SignatureOptions, type SocketEvents, type SourceOption, type SourceRef, type StaffAccessRule, type StaffSignIn, type StandardSchema, type StandardWebhookOptions, type StartJobsOptions, type StoreFileInput, type StoredMember, type StoredNotification, type StoredObject, type StoredOrganization, type StoredUser, type StrayValues, type SubscriptionDefinition, type SubscriptionEvent, type SubscriptionOptions, type TenantValue, type ToolAnnotations, type ToolCall, type ToolComment, type ToolCommentPage, type ToolComments, type ToolContext, type ToolRecord, type ToolRecords, type ToolSpec, type TrustedApp, type TurnOptions, type UnreadableEntry, type Urgency, type User, type UserCreatedHook, type VapidSettings, type ViewSource, type WebPushFields, type WebPushOptions, type WebhooksOptions, type WidgetOptions, type WriteEvent, type WriteOperation, type WriteRecordToolsInput, addAppRoleToOwners, addCommentTool, addMember, apiKeyCaller, apiKeySettings, apiKeyVariables, appNameOver, aspectRatio, assistantProtocolRoutes, assistantRoles, assistantSettings, assistantVariables, authSchemaDrift, authSchemaMigration, authStoreTables, backgroundSettled, badRequest, batchWriteTool, beforeSignInPluginsVariable, betterAuthTokens, capSocketMessages, changesMigration, checkAi, checkAuthSchema, checkChanges, checkComments, checkComputed, checkJobsSchema, checkNotificationsSchema, checkQueryRunner, checkRealtimeRelay, checkResourcesOutsideAuthStore, checkSourceNames, checkViewQueries, checkWebhooksSchema, coalesce, commentTools, commentsMigration, computedMigration, configExports, consoleAuditQueue, conversationKey, countRecordsTool, createAdmin, createConversations, createEncryptionTools, createFileCleanup, createOrganization, createRecordTool, createUser, defaultAppName, defaultHistoryPage, defaultSignInPolicy, defineEmail, defineFunction, defineJob, defineTool, deleteRecordTool, deleteUser, describeResourceTool, deviceIdParam, deviceStore, devicesPath, enqueueJob, errorReportingSettings, errorReportingVariable, eventMatcher, fileConversationStore, fileSize, fileType, forbidden, formatUri, functionApp, generateVapidKeys, getRecordTool, goTruePath, handleDroppedConnections, hasUsers, historyIdParam, historyIdPattern, historyLimits, historyPath, historyStore, honorSocketMessageCaps, imageSize, isBackgroundWork, isCaptured, isJobDefinition, isOAuthWellKnownPath, isSchedule, issueToken, jobDefinitions, jobsDrainApp, jobsSchema, jobsSchemaMigration, jwtAuthenticator, jwtVerifier, limitedFileStore, listCommentsTool, listOrganizations, listRecordsTool, listResourcesTool, listUsers, localFileStore, longQueryTimeoutMs, mapSettings, mapStyleUrl, mapStyleVariable, maxDevicesPerUser, maxHistoryPage, maxMessageBytes, maxRecipients, maxTokenTtlSeconds, maxTtlSeconds, maxUnreadCount, maxWidgetPropsBytes, mcpApprovals, mcpGate, mcpHandler, mcpIcons, mcpInstructions, mcpRoutes, mcpServer, mcpToolContext, mcpTools, migrationCommand, newWebhookSecret, normalizeRoles, notFound, notificationSenders, notificationsMigration, oauthWellKnownPaths, objectKey, parseColumns, parseRoles, passwordLength, pluginOptions, pluginsBeforeSignIn, pluginsFor, pluginsVariable, pngIcons, poolWaitMs, postgresDeviceStore, postgresHistoryStore, processor, pushMessage, queryRunnerMigration, readDbConnections, readJson, readOnlyQueryTool, readOperatorSettings, readOutbox, readPlatformSignIn, readRecordTools, readVapidSettings, readWriteQueryTool, readableResources, realtimeLimits, realtimeRelayMigration, recordOf, relayed, removeDevicesWithUsers, removeHistoryWithUsers, removeMember, renderVariant, requestApproval, requireEnv, resourceChange, roleChoices, runInBackground, runReadOnlyQuery, runReadWriteQuery, runTurn, runtimeUrl, runtimeVariable, s3FileStore, seesAssistant, seesRuntime, sendNotification, sessionOf, setMemberRoles, setUserBanned, setUserRole, shownAppName, signInPolicyMethods, socketMessageCapOf, sourceOptions, sourcesFor, sourcesVariable, startErrorReporting, startJobs, storageCleanupSchedule, storageProvider, storeFile, storeUsage, streamChatCompletion, subscription, supabasePath, thumbHash, unauthorized, updateRecordTool, urgencies, vapidPrivateKeyVariable, vapidPublicKeyVariable, vapidSubjectVariable, variantPath, verifySignature, verifyStandardWebhook, waitUntil, wantsLongQueries, webManifestPath, webPushSender, webauthnPath, webhooksMigration, widget, withCacheBreakpoints, withTrustedApps, writeRecordTools };
174
+ export { type Admin, type AdminAuth, type AdminOptions, type AggregateParams, type ApiFunction, type ApiKeys, type ApiKeysOptions, type ApnsEnvironment, type AppIcons, type AppIdentity, type AppPoolConfig, type ApplyOptions, type ApplyResult, type ApprovalAnswer, type ApprovalRequest, type ArgumentsPayload, type AssistantBackend, type AssistantOptions, type AssistantSettings, type AssistantTool, type AuditEvent, type AuditQueue, type AuthHooks, type AuthSettings, type AuthenticateSettings, type Authenticator, type BaseToolContext, type BatchOperation, type BatchResult, type BetterAuthAuthenticator, type BetterAuthAuthenticatorOptions, type Caller, type CallerOptions, type CapturedRow, type CascadingKey, type ChatMessage, type ChatTextPart, type CheckAiInput, type CleanupEntry, type CleanupReport, type CleanupSchedule, type CoalescedChange, type CommentItem, type CommentToolsInput, type CommentUsers, type Completion, type CompletionOptions, ConnectionsBusy, type Conversation, type ConversationRecord, type ConversationStore, type ConversationsOptions, type CorsOptions, type CorsOrigins, type CreateAdminInput, type CreateAuthOptions, type DecryptField, type Device, type DeviceColumn, type DeviceKind, type DeviceStore, DeviceStoreError, type DrainResult, type EmailComponent, type EmailOptions, type EmailTemplate, type EncryptionStatus, type EncryptionTools, type EncryptionToolsInput, type EnqueueJob, type EnqueueOptions, type ErrorReporter, type ErrorReportingOptions, type ErrorReportingSettings, type EventData, type EventsOptions, FatalJobError, type FieldApplied, type FieldDecrypter, type FieldReader, type FieldStatus, type FileCleanupInput, type FileLimits, type FileObject, type FileProvider, type FileProviderSettings, type FileRef, type FileStore, type FileVariantObject, type FilesOptions, type FunctionApp, type FunctionCaller, type FunctionContext, type FunctionEnv, type FunctionHandler, type FunctionOptions, type FunctionRecords, type FunctionSocket, type FunctionSource, type HistoryColumn, type HistoryOptions, type HistoryPosition, type HistoryStore, HistoryStoreError, type HookContext, HttpProblem, type IssueTokenOptions, type JobContext, type JobDeclaration, type JobDefinition, type JobName, type JobOptions, type JobPayload, type JobRun, type JobsRuntime, type JsonObject, type JsonValue, type JwtOptions, type JwtVerifyOptions, type KeyFunctionContext, type LinkedAccount, type ListParams, type LocalFilesOptions, type MailMessage, type Mailer, type MapLayer, type MapOptions, type MapSettings, type McpApprovals, type McpGateInput, type McpHandlerInput, type McpRoutesInput, type McpServerInput, type McpToolsInput, type McpWrites, type MemberInput, type Membership, MissingCredentials, type MobileConfig, ModelError, type ModelSettings, type NewDevice, type NewNotification, type NewOrganization, type NewUser, type NotificationRecipients, NotificationSendError, type NotificationsOptions, type OperatorProvider, type OrganizationRole, type OrganizationsOptions, type PgModule, type PipelineHook, type PlatformSignIn, type PluginOption, type PluginRef, type PngIcon, type ProtectedFunctionOptions, type PublicFunctionContext, type PublicFunctionEnv, type PublicFunctionHandler, type PublicFunctionOptions, type PushAnswer, type PushMessage, PushMessageError, type PushSender, type QueryOptions, type QueryResult, type ReadableResources, type RealtimeOptions, type RealtimePrune, type ReasoningDetail, type ReasoningEffort, type RebindOption, type RecordGroups, type RecordKey, type RecordKeyInput, type RecordPage, type RenderedEmail, type ResourceChange, type ResourceSource, type RoleDefinition, type RolesInput, type RunContext, type RuntimeOptions, type S3Bucket, type S3FilesOptions, type S3ListPage, type S3Object, type ScanGuardMode, type ScheduledDelete, type SendNotification, type Session, type SessionOrganization, type Sharp, type SignInPolicy, type SignInRule, type SignatureOptions, type SocketEvents, type SourceOption, type SourceRef, type StaffAccessRule, type StaffSignIn, type StandardSchema, type StandardWebhookOptions, type StartJobsOptions, type StoreFileInput, type StoredMember, type StoredNotification, type StoredObject, type StoredOrganization, type StoredUser, type StrayValues, type SubscriptionDefinition, type SubscriptionEvent, type SubscriptionOptions, type TenantValue, type ToolAnnotations, type ToolCall, type ToolComment, type ToolCommentPage, type ToolComments, type ToolContext, type ToolRecord, type ToolRecords, type ToolSpec, type TrustedApp, type TurnOptions, type UnreadableEntry, type Urgency, type User, type UserCreatedHook, type VapidSettings, type ViewSource, type WebPushFields, type WebPushOptions, type WebhooksOptions, type WidgetOptions, type WriteEvent, type WriteOperation, type WriteRecordToolsInput, addAppRoleToOwners, addCommentTool, addMember, apiKeyCaller, apiKeySettings, apiKeyVariables, appNameOver, aspectRatio, assistantProtocolRoutes, assistantRoles, assistantSettings, assistantVariables, authSchemaDrift, authSchemaMigration, authStoreTables, backgroundSettled, badRequest, batchWriteTool, beforeSignInPluginsVariable, betterAuthTokens, capSocketMessages, changesMigration, checkAi, checkAuthSchema, checkChanges, checkComments, checkComputed, checkJobsSchema, checkNotificationsSchema, checkQueryRunner, checkRealtimeRelay, checkResourcesOutsideAuthStore, checkSourceNames, checkViewQueries, checkWebhooksSchema, coalesce, commentTools, commentsMigration, computedMigration, configExports, consoleAuditQueue, conversationKey, countRecordsTool, createAdmin, createConversations, createEncryptionTools, createFileCleanup, createOrganization, createRecordTool, createUser, defaultAppName, defaultHistoryPage, defaultSignInPolicy, defineEmail, defineFunction, defineJob, defineTool, deleteRecordTool, deleteUser, describeResourceTool, deviceIdParam, deviceStore, devicesPath, enqueueJob, errorReportingSettings, errorReportingVariable, eventMatcher, fileConversationStore, fileSize, fileType, forbidden, formatUri, functionApp, generateVapidKeys, getRecordTool, goTruePath, handleDroppedConnections, hasUsers, historyIdParam, historyIdPattern, historyLimits, historyPath, historyStore, honorSocketMessageCaps, imageSize, isBackgroundWork, isCaptured, isJobDefinition, isOAuthWellKnownPath, isSchedule, issueToken, jobDefinitions, jobsDrainApp, jobsSchema, jobsSchemaMigration, jwtAuthenticator, jwtVerifier, limitedFileStore, listCommentsTool, listOrganizations, listRecordsTool, listResourcesTool, listUsers, localFileStore, longQueryTimeoutMs, mapSettings, mapStyleUrl, mapStyleVariable, maxDevicesPerUser, maxHistoryPage, maxMessageBytes, maxRecipients, maxTokenTtlSeconds, maxTtlSeconds, maxUnreadCount, maxWidgetPropsBytes, mcpApprovals, mcpGate, mcpHandler, mcpIcons, mcpInstructions, mcpRoutes, mcpServer, mcpToolContext, mcpTools, migrationCommand, newWebhookSecret, normalizeRoles, notFound, notificationSenders, notificationsMigration, oauthWellKnownPaths, objectKey, parseColumns, parseRoles, passwordLength, pluginOptions, pluginsBeforeSignIn, pluginsFor, pluginsVariable, pngIcons, poolWaitMs, postgresDeviceStore, postgresHistoryStore, processor, pushMessage, queryRunnerMigration, readDbConnections, readJson, readOnlyQueryTool, readOperatorSettings, readOutbox, readPlatformSignIn, readRecordTools, readVapidSettings, readWriteQueryTool, readableResources, realtimeLimits, realtimeRelayMigration, recordOf, refusalOf, refused, relayed, removeDevicesWithUsers, removeHistoryWithUsers, removeMember, renderVariant, requestApproval, requireEnv, resourceChange, roleChoices, runInBackground, runReadOnlyQuery, runReadWriteQuery, runTurn, runtimeUrl, runtimeVariable, s3FileStore, seesAssistant, seesRuntime, sendNotification, sessionOf, setMemberRoles, setUserBanned, setUserRole, shownAppName, signInPolicyMethods, socketMessageCapOf, sourceOptions, sourcesFor, sourcesVariable, startErrorReporting, startJobs, storageCleanupSchedule, storageProvider, storeFile, storeUsage, streamChatCompletion, subscription, supabasePath, thumbHash, unauthorized, updateRecordTool, urgencies, vapidPrivateKeyVariable, vapidPublicKeyVariable, vapidSubjectVariable, variantPath, verifySignature, verifyStandardWebhook, waitUntil, wantsLongQueries, webManifestPath, webPushSender, webauthnPath, webhooksMigration, widget, withCacheBreakpoints, withTrustedApps, writeRecordTools };
package/dist/index.js CHANGED
@@ -44,6 +44,7 @@ import { mcpToolContext } from "./mcp/mcp-context.js";
44
44
  import { mcpGate, sessionOf } from "./mcp/mcp-gate.js";
45
45
  import { mcpHandler } from "./mcp/mcp-handler.js";
46
46
  import { mcpRoutes } from "./mcp/mcp-routes.js";
47
+ import { refusalOf, refused } from "./assistant/record-tool-args.js";
47
48
  import { mcpInstructions } from "./mcp/mcp-instructions.js";
48
49
  import { mcpServer } from "./mcp/mcp-server.js";
49
50
  import { countRecordsTool } from "./assistant/count-records-tool.js";
@@ -126,4 +127,4 @@ import { enqueueJob } from "./jobs/declared-job.js";
126
127
  import { defineEmail } from "./mail/define-email.js";
127
128
  import { startJobs } from "./jobs/runtime.js";
128
129
  import { jobsDrainApp } from "./jobs/drain-route.js";
129
- export { ConnectionsBusy, DeviceStoreError, FatalJobError, HistoryStoreError, HttpProblem, MissingCredentials, ModelError, NotificationSendError, PushMessageError, addAppRoleToOwners, addCommentTool, addMember, apiKeyCaller, apiKeySettings, apiKeyVariables, appNameOver, aspectRatio, assistantProtocolRoutes, assistantRoles, assistantSettings, assistantVariables, authSchemaDrift, authSchemaMigration, authStoreTables, backgroundSettled, badRequest, batchWriteTool, beforeSignInPluginsVariable, betterAuthTokens, capSocketMessages, changesMigration, checkAi, checkAuthSchema, checkChanges, checkComments, checkComputed, checkJobsSchema, checkNotificationsSchema, checkQueryRunner, checkRealtimeRelay, checkResourcesOutsideAuthStore, checkSourceNames, checkViewQueries, checkWebhooksSchema, coalesce, commentTools, commentsMigration, computedMigration, configExports, consoleAuditQueue, conversationKey, countRecordsTool, createAdmin, createConversations, createEncryptionTools, createFileCleanup, createOrganization, createRecordTool, createUser, defaultAppName, defaultHistoryPage, defaultSignInPolicy, defineEmail, defineFunction, defineJob, defineTool, deleteRecordTool, deleteUser, describeResourceTool, deviceIdParam, deviceStore, devicesPath, enqueueJob, errorReportingSettings, errorReportingVariable, eventMatcher, fileConversationStore, fileSize, fileType, forbidden, formatUri, functionApp, generateVapidKeys, getRecordTool, goTruePath, handleDroppedConnections, hasUsers, historyIdParam, historyIdPattern, historyLimits, historyPath, historyStore, honorSocketMessageCaps, imageSize, isBackgroundWork, isCaptured, isJobDefinition, isOAuthWellKnownPath, isSchedule, issueToken, jobDefinitions, jobsDrainApp, jobsSchema, jobsSchemaMigration, jwtAuthenticator, jwtVerifier, limitedFileStore, listCommentsTool, listOrganizations, listRecordsTool, listResourcesTool, listUsers, localFileStore, longQueryTimeoutMs, mapSettings, mapStyleUrl, mapStyleVariable, maxDevicesPerUser, maxHistoryPage, maxMessageBytes, maxRecipients, maxTokenTtlSeconds, maxTtlSeconds, maxUnreadCount, maxWidgetPropsBytes, mcpApprovals, mcpGate, mcpHandler, mcpIcons, mcpInstructions, mcpRoutes, mcpServer, mcpToolContext, mcpTools, migrationCommand, newWebhookSecret, normalizeRoles, notFound, notificationSenders, notificationsMigration, oauthWellKnownPaths, objectKey, parseColumns, parseRoles, passwordLength, pluginOptions, pluginsBeforeSignIn, pluginsFor, pluginsVariable, pngIcons, poolWaitMs, postgresDeviceStore, postgresHistoryStore, processor, pushMessage, queryRunnerMigration, readDbConnections, readJson, readOnlyQueryTool, readOperatorSettings, readOutbox, readPlatformSignIn, readRecordTools, readVapidSettings, readWriteQueryTool, readableResources, realtimeLimits, realtimeRelayMigration, recordOf, relayed, removeDevicesWithUsers, removeHistoryWithUsers, removeMember, renderVariant, requestApproval, requireEnv, resourceChange, roleChoices, runInBackground, runReadOnlyQuery, runReadWriteQuery, runTurn, runtimeUrl, runtimeVariable, s3FileStore, seesAssistant, seesRuntime, sendNotification, sessionOf, setMemberRoles, setUserBanned, setUserRole, shownAppName, signInPolicyMethods, socketMessageCapOf, sourceOptions, sourcesFor, sourcesVariable, startErrorReporting, startJobs, storageCleanupSchedule, storageProvider, storeFile, storeUsage, streamChatCompletion, subscription, supabasePath, thumbHash, unauthorized, updateRecordTool, urgencies, vapidPrivateKeyVariable, vapidPublicKeyVariable, vapidSubjectVariable, variantPath, verifySignature, verifyStandardWebhook, waitUntil, wantsLongQueries, webManifestPath, webPushSender, webauthnPath, webhooksMigration, widget, withCacheBreakpoints, withTrustedApps, writeRecordTools };
130
+ export { ConnectionsBusy, DeviceStoreError, FatalJobError, HistoryStoreError, HttpProblem, MissingCredentials, ModelError, NotificationSendError, PushMessageError, addAppRoleToOwners, addCommentTool, addMember, apiKeyCaller, apiKeySettings, apiKeyVariables, appNameOver, aspectRatio, assistantProtocolRoutes, assistantRoles, assistantSettings, assistantVariables, authSchemaDrift, authSchemaMigration, authStoreTables, backgroundSettled, badRequest, batchWriteTool, beforeSignInPluginsVariable, betterAuthTokens, capSocketMessages, changesMigration, checkAi, checkAuthSchema, checkChanges, checkComments, checkComputed, checkJobsSchema, checkNotificationsSchema, checkQueryRunner, checkRealtimeRelay, checkResourcesOutsideAuthStore, checkSourceNames, checkViewQueries, checkWebhooksSchema, coalesce, commentTools, commentsMigration, computedMigration, configExports, consoleAuditQueue, conversationKey, countRecordsTool, createAdmin, createConversations, createEncryptionTools, createFileCleanup, createOrganization, createRecordTool, createUser, defaultAppName, defaultHistoryPage, defaultSignInPolicy, defineEmail, defineFunction, defineJob, defineTool, deleteRecordTool, deleteUser, describeResourceTool, deviceIdParam, deviceStore, devicesPath, enqueueJob, errorReportingSettings, errorReportingVariable, eventMatcher, fileConversationStore, fileSize, fileType, forbidden, formatUri, functionApp, generateVapidKeys, getRecordTool, goTruePath, handleDroppedConnections, hasUsers, historyIdParam, historyIdPattern, historyLimits, historyPath, historyStore, honorSocketMessageCaps, imageSize, isBackgroundWork, isCaptured, isJobDefinition, isOAuthWellKnownPath, isSchedule, issueToken, jobDefinitions, jobsDrainApp, jobsSchema, jobsSchemaMigration, jwtAuthenticator, jwtVerifier, limitedFileStore, listCommentsTool, listOrganizations, listRecordsTool, listResourcesTool, listUsers, localFileStore, longQueryTimeoutMs, mapSettings, mapStyleUrl, mapStyleVariable, maxDevicesPerUser, maxHistoryPage, maxMessageBytes, maxRecipients, maxTokenTtlSeconds, maxTtlSeconds, maxUnreadCount, maxWidgetPropsBytes, mcpApprovals, mcpGate, mcpHandler, mcpIcons, mcpInstructions, mcpRoutes, mcpServer, mcpToolContext, mcpTools, migrationCommand, newWebhookSecret, normalizeRoles, notFound, notificationSenders, notificationsMigration, oauthWellKnownPaths, objectKey, parseColumns, parseRoles, passwordLength, pluginOptions, pluginsBeforeSignIn, pluginsFor, pluginsVariable, pngIcons, poolWaitMs, postgresDeviceStore, postgresHistoryStore, processor, pushMessage, queryRunnerMigration, readDbConnections, readJson, readOnlyQueryTool, readOperatorSettings, readOutbox, readPlatformSignIn, readRecordTools, readVapidSettings, readWriteQueryTool, readableResources, realtimeLimits, realtimeRelayMigration, recordOf, refusalOf, refused, relayed, removeDevicesWithUsers, removeHistoryWithUsers, removeMember, renderVariant, requestApproval, requireEnv, resourceChange, roleChoices, runInBackground, runReadOnlyQuery, runReadWriteQuery, runTurn, runtimeUrl, runtimeVariable, s3FileStore, seesAssistant, seesRuntime, sendNotification, sessionOf, setMemberRoles, setUserBanned, setUserRole, shownAppName, signInPolicyMethods, socketMessageCapOf, sourceOptions, sourcesFor, sourcesVariable, startErrorReporting, startJobs, storageCleanupSchedule, storageProvider, storeFile, storeUsage, streamChatCompletion, subscription, supabasePath, thumbHash, unauthorized, updateRecordTool, urgencies, vapidPrivateKeyVariable, vapidPublicKeyVariable, vapidSubjectVariable, variantPath, verifySignature, verifyStandardWebhook, waitUntil, wantsLongQueries, webManifestPath, webPushSender, webauthnPath, webhooksMigration, widget, withCacheBreakpoints, withTrustedApps, writeRecordTools };
@@ -1,8 +1,8 @@
1
- import { AssistantTool, ToolContext } from "../assistant/tools.js";
1
+ import { AssistantTool, BaseToolContext, ToolContext } from "../assistant/tools.js";
2
2
  import { McpApprovals } from "./mcp-approval-store.js";
3
3
  import { Icon, McpServer } from "@modelcontextprotocol/server";
4
4
  //#region src/mcp/mcp-server.d.ts
5
- export type McpServerInput = {
5
+ export type McpServerInput<Context extends BaseToolContext = ToolContext> = {
6
6
  /** The name, version, title and icons the server tells clients when they connect, each icon an absolute URL. */
7
7
  info: {
8
8
  name: string;
@@ -12,10 +12,13 @@ export type McpServerInput = {
12
12
  };
13
13
  /** What the server tells clients about using it when they connect; `mcpInstructions`, on reading records, by default. */
14
14
  instructions?: string;
15
- tools: AssistantTool[];
16
- /** What each tool gets as its context, for the caller of the request; `approve` comes from each call's own answers. */
17
- context: Omit<ToolContext, 'approve'>;
18
- /** Gets the errors a tool throws, which the client only sees as a failure. */
15
+ tools: AssistantTool<Context>[];
16
+ /**
17
+ * What each tool gets as its context, for the caller of the request; `approve` comes from each call's own answers.
18
+ * A `ToolContext`, with the app's records, unless every tool takes a smaller one, such as `BaseToolContext`.
19
+ */
20
+ context: Omit<Context, 'approve'>;
21
+ /** Gets the errors a tool throws other than refusals, which the client only sees as a failure. */
19
22
  report: (error: unknown) => void;
20
23
  /** The roles whose calls are approved without asking the client: a user holding one of them is never asked. None by default. */
21
24
  rolesWithoutApproval?: readonly string[];
@@ -23,10 +26,12 @@ export type McpServerInput = {
23
26
  approvals: McpApprovals;
24
27
  };
25
28
  /**
26
- * An MCP server offering `tools` as MCP tools, each with its JSON Schema, its hints, and the text it returns. A tool
29
+ * An MCP server offering `tools` as MCP tools, each with its JSON Schema, its hints, its `title` and `_meta`, and the
30
+ * text it returns. A tool that throws an `HttpProblem` below 500, or a query error the REST API would answer below 500,
31
+ * refuses the call with `{ error, message }`, unreported; anything else it throws is reported and fails the call. A tool
27
32
  * that asks for approval makes the call ask the client's user, and runs again from the start with their answer, which
28
33
  * counts only for the call it was asked for, once, while it lasts; for a user holding one of `rolesWithoutApproval` it
29
34
  * is approved at once, and the client is never asked.
30
35
  */
31
- export declare const mcpServer: ({ info, instructions, tools, context, report, rolesWithoutApproval, approvals }: McpServerInput) => McpServer;
36
+ export declare const mcpServer: <Context extends BaseToolContext = ToolContext>({ info, instructions, tools, context, report, rolesWithoutApproval, approvals }: McpServerInput<Context>) => McpServer;
32
37
  //#endregion
@@ -1,5 +1,6 @@
1
1
  import { isStatementTimeout } from "../statement-timeout.js";
2
2
  import { checkedTools } from "../assistant/checked-tools.js";
3
+ import { refusalOf } from "../assistant/record-tool-args.js";
3
4
  import { ApprovalNeeded, approvalAsked, approvedUnasked, mcpApproval, writesUnasked } from "./mcp-approval.js";
4
5
  import { callHash, callScope, scopeHash } from "./mcp-call-hash.js";
5
6
  import { mcpInstructions } from "./mcp-instructions.js";
@@ -21,6 +22,13 @@ const failed = {
21
22
  }],
22
23
  isError: true
23
24
  };
25
+ const refusal = (text) => ({
26
+ content: [{
27
+ type: "text",
28
+ text
29
+ }],
30
+ isError: true
31
+ });
24
32
  const stopped = (tool) => ({
25
33
  content: [{
26
34
  type: "text",
@@ -29,7 +37,9 @@ const stopped = (tool) => ({
29
37
  isError: true
30
38
  });
31
39
  /**
32
- * An MCP server offering `tools` as MCP tools, each with its JSON Schema, its hints, and the text it returns. A tool
40
+ * An MCP server offering `tools` as MCP tools, each with its JSON Schema, its hints, its `title` and `_meta`, and the
41
+ * text it returns. A tool that throws an `HttpProblem` below 500, or a query error the REST API would answer below 500,
42
+ * refuses the call with `{ error, message }`, unreported; anything else it throws is reported and fails the call. A tool
33
43
  * that asks for approval makes the call ask the client's user, and runs again from the start with their answer, which
34
44
  * counts only for the call it was asked for, once, while it lasts; for a user holding one of `rolesWithoutApproval` it
35
45
  * is approved at once, and the client is never asked.
@@ -41,7 +51,9 @@ const mcpServer = ({ info, instructions = mcpInstructions, tools, context, repor
41
51
  const config = {
42
52
  description: tool.description,
43
53
  inputSchema: inputSchemaOf(tool.parameters),
44
- ...tool.annotations && { annotations: tool.annotations }
54
+ ...tool.title !== void 0 && { title: tool.title },
55
+ ...tool.annotations && { annotations: tool.annotations },
56
+ ...tool._meta && { _meta: tool._meta }
45
57
  };
46
58
  const answer = async (args, ctx) => {
47
59
  const bound = () => {
@@ -78,6 +90,8 @@ const mcpServer = ({ info, instructions = mcpInstructions, tools, context, repor
78
90
  try {
79
91
  return await answer(args, ctx);
80
92
  } catch (error) {
93
+ const refusing = refusalOf(error);
94
+ if (refusing !== void 0) return refusal(refusing);
81
95
  report(error);
82
96
  return isStatementTimeout(error) ? stopped(tool.name) : failed;
83
97
  }
package/dist/package.js CHANGED
@@ -1,4 +1,4 @@
1
1
  //#region package.json
2
- var version = "0.58.2";
2
+ var version = "0.58.3";
3
3
  //#endregion
4
4
  export { version };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@protobase/server",
3
- "version": "0.58.2",
3
+ "version": "0.58.3",
4
4
  "description": "The Protobase REST API as a Hono app, with Better Auth sign-in.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -41,9 +41,9 @@
41
41
  "@better-auth/passkey": "^1.7.12",
42
42
  "@better-auth/sso": "^1.7.12",
43
43
  "@modelcontextprotocol/server": "^2.3.1",
44
- "@protobase/layout": "0.58.2",
45
- "@protobase/query": "0.58.2",
46
- "@protobase/schema": "0.58.2",
44
+ "@protobase/layout": "0.58.3",
45
+ "@protobase/query": "0.58.3",
46
+ "@protobase/schema": "0.58.3",
47
47
  "@react-email/render": "^2.1.0",
48
48
  "@scalar/hono-api-reference": "^0.12.10",
49
49
  "@sentry/core": "^11.7.0",