Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 36 additions & 1 deletion docs/docs/api/appkit/TypeAlias.Plugins.md

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion docs/docs/api/appkit/index.md

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 12 additions & 0 deletions docs/docs/plugins/agents.md
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,18 @@ Some examples further down still pass agents inline via this map for snippet bre
| `prefix` | `{ prefix: "" }` | Drop the `${pluginName}.` prefix |
| `rename` | `{ rename: { query: "q" } }` | Remap specific local names |

Named analytics SQL files can also be exposed as individual tools, separately
from the raw SQL toolkit:

```ts
tools: (plugins) => ({
...plugins.analytics.queries({ only: ["top_customers"] }),
}),
```

See [Named queries as tools](./analytics.md#named-queries-as-tools) for identity,
parameter, and read-only rules.

For plugins that don't expose a `.toolkit()` method (e.g., third-party `ToolProvider` plugins authored with plain `toPlugin`), the runtime falls back to walking `getAgentTools()` and synthesizing namespaced keys (`${pluginName}.${localName}`). The fallback respects `only` / `except` / `rename` / `prefix` the same way.

If a referenced plugin is not registered in `createApp({ plugins })`, the agents plugin throws at setup with an `Available: …` listing so you can fix the wiring before the first request.
Expand Down
48 changes: 48 additions & 0 deletions docs/docs/plugins/analytics.md
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,54 @@ type-based placeholder, so a sample value can never break out of the
WHERE workspace_id = :workspaceId
```

## Named queries as tools

Expose named queries explicitly in an agent. `queries()` returns keys such as
`query.top_customers`; it does not include the raw SQL tool from `toolkit()`.

```ts
const agent = createAgent({
instructions: "Answer questions about customers.",
tools: (plugins) => ({
...plugins.analytics.queries({ only: ["top_customers"] }),
}),
});
```

Write descriptions for the model in the SQL file:

```sql
-- @description Find customers with the most orders.
-- @param min_orders INT Minimum number of orders
-- @param region STRING Region to search
SELECT customer, count(*) AS orders FROM sales
WHERE region = :region AND workspace_id = :workspaceId
GROUP BY customer HAVING count(*) >= :min_orders
```

Multiple `@description` lines are joined. Without one, AppKit warns and uses a
generic description. Only actual `:name` markers become required inputs;
untyped inputs are strings. `workspaceId` is injected by the server and is not
exposed to the model. A `-- @param x TYPE = sample` line supplies a typegen
sample, not a tool-parameter description. See [sample values](#sample-values-for-type-generation).

`.sql` tools always run as the app service principal, even within a user
request. `.obo.sql` tools run as the caller and require caller credentials
(except for the existing local-development fallback). If both variants exist,
the OBO file wins. Only expose app-identity queries to agents whose users may
see the data available to the app. The same conservative read-only SQL check
used by the raw analytics tool applies; an invalid explicit selection fails at
startup, while an invalid query discovered without `only` is skipped with a
warning. The classifier checks statement prefixes; it does not guarantee that
functions or CTEs have no side effects. Use warehouse permissions to enforce
read-only access. Tool lists are built at startup, so restart after adding or
changing queries. Results contain `rows` and `rowCount`; results over 100 rows are
truncated with a note. This limit applies after fetching, not at the warehouse.

For application code, `appkit.analytics.runQuery(name, parameters?, signal?)`
returns uncapped rows and accepts the usual SQL type markers. It follows the
same app/caller identity rules.

## HTTP endpoints

The analytics plugin exposes these endpoints (mounted under `/api/analytics`):
Expand Down
1 change: 1 addition & 0 deletions packages/appkit/src/core/agent/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ export {
type Plugins,
type PluginToolkitProvider,
type PromptContext,
type QueryToolsOptions,
type RegisteredAgent,
type ResolvedToolEntry,
type ToolkitEntry,
Expand Down
3 changes: 3 additions & 0 deletions packages/appkit/src/core/agent/run-agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -515,6 +515,9 @@ function buildStandalonePluginsMap(
if (!provider) continue; // initStandalonePlugins should have set this
out[data.name] = {
toolkit: (opts) => resolveToolkitFromProvider(data.name, provider, opts),
...("queries" in provider && typeof provider.queries === "function"
? { queries: provider.queries.bind(provider) }
: {}),
};
}
return createPluginsProxy(out, "runAgent: tools(plugins)");
Expand Down
39 changes: 39 additions & 0 deletions packages/appkit/src/core/agent/tests/run-agent.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,45 @@ describe("runAgent", () => {
expect(pingExec).toHaveBeenCalled();
});

test("standalone passes analytics queries through to tools callback", async () => {
const queries = vi.fn(function (this: { name: string }, opts: unknown) {
expect(this.name).toBe("analytics");
expect(opts).toEqual({ only: ["sales"] });
return {};
});
class FakeAnalytics implements ToolProvider {
static manifest = { name: "analytics" };
static DEFAULT_CONFIG = {};
name = "analytics";
constructor(public config: unknown) {}
getAgentTools(): AgentToolDefinition[] {
return [];
}
async executeAgentTool() {
return undefined;
}
queries = queries;
}
const def = createAgent({
instructions: "x",
model: scriptedAdapter([]),
tools: (plugins) => ({
...plugins.analytics.queries({ only: ["sales"] }),
}),
});
await runAgent(def, {
messages: "hi",
plugins: [
{
plugin: FakeAnalytics as unknown as PluginConstructor,
config: {},
name: "analytics",
},
],
});
expect(queries).toHaveBeenCalledOnce();
});

test("function-form throws with guidance when a referenced plugin is missing", async () => {
const adapter: AgentAdapter = {
async *run(_input, _context) {
Expand Down
15 changes: 14 additions & 1 deletion packages/appkit/src/core/agent/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,10 +67,18 @@ export interface PluginToolkitProvider {
toolkit(opts?: ToolkitOptions): Record<string, ToolkitEntry>;
}

/** Options for `plugins.analytics.queries()`. */
export interface QueryToolsOptions {
/** Query names to expose; defaults to all named queries. */
only?: string[];
}

/**
* Plugin map passed to the function form of {@link AgentDefinition.tools}.
* Each entry exposes a `.toolkit(opts?)` method that returns a record of
* {@link ToolkitEntry} markers ready to be spread into a tool record.
* `analytics` also exposes `.queries(opts?)`, one `query.<name>` tool per
* named SQL file in `config/queries/`.
*
* AppKit does not statically know which plugins the surrounding
* `createApp` will register, so this is a plain string-keyed record.
Expand All @@ -86,12 +94,17 @@ export interface PluginToolkitProvider {
* get_weather: tool({ ... }),
* ...plugins.analytics.toolkit(),
* ...plugins.files.toolkit({ only: ["uploads.read"] }),
* ...plugins.analytics.queries({ only: ["top_customers"] }),
* };
* },
* });
* ```
*/
export type Plugins = Record<string, PluginToolkitProvider>;
export type Plugins = Record<string, PluginToolkitProvider> & {
analytics: PluginToolkitProvider & {
queries(opts?: QueryToolsOptions): Record<string, ToolkitEntry>;
};
};

/**
* Context passed to `baseSystemPrompt` callbacks.
Expand Down
Loading
Loading