Skip to main content

Prompt cookbook

With the MCP server connected, you build a Cogneris integration by describing it. These prompts work as written in the agent chat of VS Code, Visual Studio, Cursor and Claude Code — paste one, adjust the names and paths to your project, and review what the assistant proposes before you accept it.

This video shows the whole flow in VS Code: an API key, Python extraction and classification, and a webhook with a verified signature.

Cogneris MCP: Cogneris in VS Code: MCP, API keys, Python code and webhooks Watch on YouTube
Use Agent mode

In VS Code and Visual Studio, the Cogneris tools are only available when Copilot Chat is in Agent mode.

How to write a prompt that works the first time​

  • Say "Cogneris". It tells the assistant to use the Cogneris tools instead of guessing the API.
  • Name the language and framework if the project does not make it obvious — ".NET 8 minimal API", "Node with TypeScript", "Python with FastAPI".
  • Say where secrets live. "Read the key from COGNERIS_API_KEY" keeps it out of the code.
  • Say sandbox or production. Sandbox keys (xtkt_test_…) cover the asynchronous job flow (/api/v1/artifacts and /api/v1/document-jobs); the synchronous /Document/* routes and classifiers need a production key (xtkt_live_…).
  • Ask for a test. "…and run it against samples/invoice.pdf" makes the assistant prove the integration instead of just writing it.

Integrate extraction​

Send a document to Cogneris and get its fields back as JSON.

Using Cogneris, add an InvoiceExtractor service to this .NET solution. It receives a PDF path, sends the file to the Cogneris extraction API and returns the extracted fields as a strongly typed Invoice record (supplier, invoice number, issue date, total, currency). Read the API key from COGNERIS_API_KEY and the base URL from COGNERIS_API_BASE_URL. Handle hasErrors and the 429 rate limit with a retry. Add an xUnit test that runs it against samples/invoice.pdf.

What the assistant does

  1. cogneris_whoami — confirms your tenant, environment and the API base URL to use.
  2. cogneris_docs_search and cogneris_api_reference for POST /Document/extraction — reads the request (multipart/form-data, field file, optional ComplementaryPrompt), the response envelope, the errors and the limits (10 MB per file, 50 requests per minute per key).
  3. Writes the code in your project, following the reference snippet for your language.
  4. Runs the test, if you asked for one — after checking you have a key in COGNERIS_API_KEY (create one if not).

The kind of code you get back (C#, abbreviated):

using System.Net.Http.Headers;
using System.Text.Json;

public sealed class InvoiceExtractor(HttpClient http)
{
public async Task<JsonElement> ExtractAsync(string path, CancellationToken ct = default)
{
await using var file = File.OpenRead(path);
using var form = new MultipartFormDataContent();
var part = new StreamContent(file);
part.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
form.Add(part, "file", Path.GetFileName(path));

using var response = await http.PostAsync("/Document/extraction", form, ct);
// The body is JSON even when Content-Type says text/plain.
using var body = JsonDocument.Parse(await response.Content.ReadAsStringAsync(ct));
var root = body.RootElement;
if (!response.IsSuccessStatusCode || root.GetProperty("hasErrors").GetBoolean())
throw new InvalidOperationException($"Cogneris extraction failed: {root}");

return root.GetProperty("data").GetProperty("metadata").GetProperty("fields").Clone();
}
}

// Program.cs
builder.Services.AddHttpClient<InvoiceExtractor>(c =>
{
c.BaseAddress = new Uri(builder.Configuration["COGNERIS_API_BASE_URL"] ?? "https://api-eu.cogneris.ai");
c.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", builder.Configuration["COGNERIS_API_KEY"]);
});

For high volumes: the asynchronous flow​

Using Cogneris, change the extractor to the asynchronous job flow: upload the file as an artifact, submit an Extraction document job with an Idempotency-Key derived from the file hash, and wait for the result. It must work with a sandbox key.

The assistant switches to POST /api/v1/artifacts → POST /api/v1/document-jobs → GET /api/v1/document-jobs/{jobId}, and reads the result from the job's output artifact. A retried submit with the same Idempotency-Key returns the original job instead of processing the document twice. Pair it with a webhook to stop polling.

Create an API key​

Create a sandbox Cogneris API key called invoice-importer-dev with only the scopes this project needs, and put it in .env as COGNERIS_API_KEY. Make sure .env is in .gitignore.

What the assistant does

  1. cogneris_apikeys_create — a sandbox key, with the minimum scopes for the code it has seen.
  2. Checks that .env is git-ignored, writes the value there, and does not repeat it in the chat. The value is returned once; Cogneris shows only its last four characters afterwards.

For production, say so explicitly — "create a production key…" — and the assistant asks you to confirm before creating it. To clean up later:

List my Cogneris API keys and revoke the ones not used in the last 90 days. Show me the list before revoking.

This needs a developer token with the apikeys.manage scope. Prefer the screen? Generate an API key in the platform.

APIs da Cogneris #1: Como gerar e proteger a chave de API da Cogneris (in Brazilian Portuguese) Watch on YouTube

Generate your own API on top of Cogneris​

Expose extraction to the rest of your company through an API you own, with your own auth and your own response shape.

Using Cogneris, create a new ASP.NET Core minimal API project DocumentGateway with POST /invoices/extract: it receives a PDF upload (max 10 MB), sends it to Cogneris extraction and returns { supplier, invoiceNumber, issueDate, total, currency }. Return 422 when Cogneris reports errors and 503 with Retry-After on rate limiting. Add OpenAPI, a health check, a Dockerfile, and read the Cogneris key from configuration — never from code. Create a sandbox Cogneris API key for local development.

The assistant reads both Cogneris routes with cogneris_api_reference, scaffolds the project, wires the client, creates the sandbox key into .env and, if you ask, runs the service and calls it with a sample file.

Create a webhook​

Get told when Cogneris finishes a document instead of polling.

Using Cogneris, register a webhook at https://api.example.com/hooks/cogneris for processed documents. Write the receiver in this project as an ASP.NET Core endpoint that verifies the Cogneris signature on the raw body, ignores deliveries it has already seen, and enqueues the job id. Store the signing secret in .env as COGNERIS_WEBHOOK_SECRET. Then send a test delivery and show me the result.

What the assistant does

  1. cogneris_webhooks_event_types — finds the event, com.cogneris.document.processed.v1, and checks it is live (sent today) rather than only planned.
  2. cogneris_webhooks_create — registers the endpoint. The signing secret comes back once, together with receiver code in Node, Python and C#; the assistant writes the secret to .env.
  3. Writes the receiver: verifies Cogneris-Webhook-Signature, rejects timestamps older than 300 seconds, and uses Cogneris-Webhook-Id (the same on every retry) as the idempotency key.
  4. cogneris_webhooks_test, then cogneris_webhooks_deliveries_get — sends a signed test delivery and shows the status code your receiver answered.

The signature is t=<unix seconds>,v1=<hex>: an HMAC-SHA256 of "<t>." + raw body, keyed with the signing secret base64url-decoded — keying with the secret's text never matches. This is the check the assistant writes:

static bool VerifyCogneris(byte[] rawBody, string? signatureHeader, string secret)
{
string? ts = null, v1 = null;
foreach (var part in (signatureHeader ?? "").Split(',', StringSplitOptions.TrimEntries))
{
if (part.StartsWith("t=")) ts = part[2..];
else if (part.StartsWith("v1=")) v1 = part[3..];
}
if (!long.TryParse(ts, out var t) || v1 is null) return false;
if (Math.Abs(DateTimeOffset.UtcNow.ToUnixTimeSeconds() - t) > 300) return false;
byte[] supplied;
try { supplied = Convert.FromHexString(v1); } catch (FormatException) { return false; }
var key = Base64Url.DecodeFromChars(secret);
var signed = Encoding.UTF8.GetBytes($"{t}.").Concat(rawBody).ToArray();
return CryptographicOperations.FixedTimeEquals(HMACSHA256.HashData(key, signed), supplied);
}

The endpoint must be public HTTPS on port 443 — for a receiver on your machine, expose it through a tunnel first. This needs a developer token with the webhooks.manage scope.

When a delivery fails:

Why did the last Cogneris webhook deliveries fail? Show the status codes my endpoint answered and replay the failed ones once the receiver is fixed.

APIs da Cogneris #4: Webhooks da Cogneris: assinatura HMAC, novas tentativas e idempotência (in Brazilian Portuguese) Watch on YouTube

Create your own document type​

The server ships this flow as a ready-made prompt — in VS Code, type / in the chat and pick Create and train a Cogneris classifier. Or write it:

Using Cogneris, create a classifier called "Supplier invoice" from the PDFs in samples/invoices/, train it and tell me when it is ready.

The assistant uploads the samples (up to 10 files of 10 MB each per call), starts training and follows the status until it is Finished. A finished classifier drives classification and extraction for your tenant.

Ask about your account​

How many documents and pages did we process on Cogneris in the last 7 days, per document type?

Which Cogneris API routes handle face match? Show me the request with curl.