agentleFS
cognitedatacognitedata/builder-skills/skills/call-cognite-function/SKILL.md

call-cognite-function

Skill6 starsChanged 8 days agoApache-2.0View on GitHub

Call a deployed Cognite CDF Function and retrieve its response, with Zod-validated API responses and an optional React Query hook. Use this skill whenever you need to invoke any CDF Function (by numeric function ID or external ID), pass arbitrary input data, and get a typed, validated result back — regardless of what the function does, the function has an outpt, or what shape its input/output takes. Triggers: call cognite function, invoke CDF function, run CDF function, poll CDF function, CDF Functions API, cognite function result, function call nonce.

The file

We split this skill into the rules it gives an agent

4 rules. About 0 are common, 1 is distinctive, and 3 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈1

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 3

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    ZodError: when an API response or the function's payload doesn't match its schema.

    line 73
  2. Very specific:

    Plain Error: when the call ends with status Failed/Timeout (includes the function's own error message) or polling is exhausted.

    line 74
  3. Very specific:

    Read-like functions: if a specific function is a pure read (same input → same output) and you want caching/deduping, skip the hook and wrap …

    line 96
  4. Distinctive:

    If you only know the function's external ID, resolve it first (same Zod pattern):

    line 108

≈ “Common” is an estimate: at least 1 in 5 of the 350,495 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Call Cognite Function

Invoke any deployed Cognite CDF Function, poll until it completes, and return a typed, schema-validated result.

Overview

The CDF Functions API uses a three-step protocol:

  1. Session nonce — exchange the current user token for a short-lived nonce so the function can make authenticated API calls on the user's behalf.
  2. Invoke — POST to the function's /call endpoint with your input data and the nonce.
  3. Poll → fetch — GET the call status in a loop; once "Completed", GET the /response endpoint.

Every API response is validated with Zod, so schema drift surfaces as a clear ZodError at the call site instead of an undefined three layers down. The function's own output payload can also be validated against a caller-supplied schema — which doubles as the source of the return type.

Files

FilePurpose
code/cogniteFunctionService.tsFramework-agnostic async function with Zod validation. Zero React deps. Copy into src/services/.
code/useCogniteFunction.tsReact Query (useMutation) hook wrapping the service. Copy into src/hooks/.

Dependencies: @cognite/sdk (already present in Flows/Fusion apps) and zod. The hook additionally needs @tanstack/react-query and a <QueryClientProvider> in the tree.

How to use

1. Copy the service file

callCogniteFunction<TOutput>(
  client: CogniteClient,
  functionId: string | number,
  data: unknown,
  opts?: CallCogniteFunctionOptions<TOutput>,
): Promise<TOutput>
  • functionId — numeric CDF function ID (or its string form). NOT an external ID; resolve those first (see below).
  • data — any JSON-serialisable object; the function receives it as its data argument.
  • opts.outputSchema — the recommended way to type the result. A Zod schema for the function's response payload; the return type is inferred from it and the payload is validated at runtime. Omit it and you get unknown back (then narrow it yourself).
  • opts.maxPollAttempts — default 120 (~6 min at 3 s). Increase for long-running batch jobs.
  • opts.pollIntervalMs — default 3000, with ±20 % jitter to avoid thundering-herd across tabs.
  • opts.signal — AbortSignal for cancellation (non-React contexts; the hook doesn't need it).

2. Define the output schema, not interfaces

import { z } from "zod";

const ReportOutput = z.object({
  success: z.boolean(),
  report: z.string(),
  error: z.string().optional(),
});

const result = await callCogniteFunction(client, 12345678, 
  { reportId: "abc", language: "en" },
  { outputSchema: ReportOutput },
);
// result: { success: boolean; report: string; error?: string } — validated

One schema gives you the TypeScript type and the runtime guarantee. Don't hand-write a parallel interface.

3. Handle errors

There is no custom error class — errors propagate as-is so you keep the full original context:

  • SDK HTTP errors from @cognite/sdk (auth, 4xx/5xx, throttling) — untouched.
  • ZodError when an API response or the function's payload doesn't match its schema.
  • Plain Error when the call ends with status Failed/Timeout (includes the function's own error message) or polling is exhausted. The message always includes the function ID and call ID.

Catch at whatever level makes sense; in the React hook, React Query surfaces the message via error.

4. (React) Use the hook

The hook wraps the service in a React Query useMutation. Mutation semantics are deliberate: function calls are not idempotent (each one spins a new execution and counts against the 100-concurrent limit), so you never want refetch-on-focus or remount-refetch. React Query also owns loading/error/result state and unmount safety — no AbortController plumbing needed.

const { call, isLoading, error, result, reset } = useCogniteFunction<
  MyInput,
  z.infer<typeof ReportOutput>
>(12345678, { outputSchema: ReportOutput });

// trigger on button click:
await call({ reportId: "abc", language: "en" });

Adjust the useCdfClient import to however your project exposes the SDK.

Note on generics: TypeScript has no partial inference, so specify both type params or neither. useCogniteFunction<MyInput> alone silently makes result unknown even with an outputSchema — if you don't care about typing the input, omit the generics entirely and let outputSchema drive the result type.

Read-like functions: if a specific function is a pure read (same input → same output) and you want caching/deduping, skip the hook and wrap the service in useQuery directly:

useQuery({
  queryKey: ["cdf-fn", functionId, input],
  queryFn: () => callCogniteFunction(sdk, functionId, input, { outputSchema }),
  staleTime: 5 * 60_000,
});

Finding the function ID

If you only know the function's external ID, resolve it first (same Zod pattern):

const Functions = z.object({
  items: z.array(z.object({ id: z.number(), externalId: z.string().optional() })),
});

const res = await client.get(`/api/v1/projects/${client.project}/functions`);
const fn = Functions.parse(res.data).items.find(
  (f) => f.externalId === "My_Function_ExternalId",
);
if (!fn) throw new Error("Function My_Function_ExternalId not found");

Polling behaviour

Unknown statuses returned by the API are treated as "still running" and polled through (only Failed/Timeout terminate with an error, Completed terminates with the result). This keeps the client forward-compatible if CDF adds new intermediate statuses.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.