Skip to content

Connector definition reference ​

Every member of a connector definition: identity, engines, auth methods, settings fields, actions and their access marking, guides, messages and assets.

Enterprise module

Connectors are the enterprise connectors module. A workspace without the module gets 402 from the connectors API.

You write the definition in TypeScript with defineConnector. cpc build imports it and writes connector.json, the manifest Cognipeer reads. The build checks the definition and fails on mistakes such as an unknown reference, a missing message or an invalid pattern, so most errors show up before you test.

ts
import { createKit, defineConnector, field, guide, t, z } from '@cognipeer/connector-sdk'

createKit<Settings>() returns the builders for actions, sources and auth methods, typed with your settings so ctx.settings is checked.

Top-level members ​

MemberRequiredWhat it is
idyes<publisher>.<name>. Lower case; the publisher is 1 to 40 characters and the name 1 to 64, letters, digits and -, each starting with a letter. The publisher must match the namespace of the signing key
nameyesDisplay name
descriptionyesOne sentence shown in the catalogue
categoryyesOne of document-management, project-management, crm, support, communication, commerce, finance, database, storage, developer, data, other
iconyesPath to an SVG or PNG in the package, for example ./assets/icon.svg
deploymentsyes['saas'], ['onprem'] or both
enginesyes{ console: '<range>' }. See Engines
settingsyesFields of the connector form. {} for none. See Settings fields
settingsVersion, migrationsnoVersion of the settings shape and the functions that upgrade old values. See Settings versions
authyesList of sign-in methods. See Auth methods
httpnoHow ctx.http reaches the service
permissionsyesHosts the package may call. permissions.egress is required, {} when the package makes no HTTP calls
sql, mailnoDeclare ctx.sql or ctx.mail. See Database and mail blocks
identitynoFunction that tells who the connected account is. Cognipeer uses it for Test connection and to label the account
actionsnoTools offered to agents. See Actions
mcpnoThe service's official MCP server. See MCP server
sourcesnoData sources for Knowledge Engine. See Sources
triggersnoEvents that start an agent run or a flow, by webhook or by polling. Needs engines.console of >=1.22.0. See Triggers
options, browse, rpc, uinoForm choices, pickers, calls from package screens, and the screens
guidesnoSetup guides. See Guides
limitsno{ timeoutMs, memoryMb, concurrency }. See Resource limits

A package with no actions, MCP server or sources builds with a warning.

Engines ​

engines.console is the range of Cognipeer versions the package runs on: comparators separated by spaces, all of which must hold, such as >=1.20.0 <2.0.0. The operators are >=, <=, >, < and =. Cognipeer refuses to install a package whose range does not include its own version.

Set the lower bound to the first Cognipeer version that has everything the package uses. This matters most for the host operations: a package that declares sql, mail, a signing inject kind or http.profile must not be published with a lower bound that predates them, because an older Cognipeer cannot refuse what it does not know.

cpc build adds engines.sdk, the SDK version the package was built with.

Resource limits ​

limits asks for less or more than the defaults. Cognipeer clamps the values.

MemberDefaultRangeMeaning
timeoutMs60 000millisecondsLongest time one call may run
memoryMb25664 to 2048Memory of the package process
concurrency81 to 32Calls the process serves at once; more calls wait

Messages and i18n ​

Every text a person reads is a message key: t('settings.baseUrl'). The definition holds the key, and i18n/en.json and i18n/tr.json hold the text. Both files are required, and cpc build fails if a key is missing in either.

  • Keys use letters, digits, _, . and -, at most 120 characters.
  • A literal string is accepted where text is expected, but it must not start with i18n:.
  • The description of an action is the exception: it is plain English text written for the model, at most 1024 characters.
  • ctx.t(key, { name: 'value' }) returns a message at run time and replaces {name} placeholders.

Settings fields ​

settings is an object of fields. Settings are plain values such as a URL, a choice or a switch. Secrets never go in settings; they belong to an auth method. Keys start with a letter, then letters, digits, _ or -, up to 64 characters.

Options every field takes:

OptionMeaning
labelText of the label (required)
helpText shown under the field
requiredThe field must be filled while it is active
defaultValue used when the field is empty
deployments['saas'] or ['onprem']. Cognipeer drops the field, and any option with the same deployments, on the other deployment before your code runs. Your code then sees undefined
visibleWhenA condition. While it is false the field is hidden and dropped
advancedShows the field in the advanced part of the form

Field kinds and their own options:

BuilderValueOptions and validation
field.textstringplaceholder, pattern (regular expression), maxLength
field.secretstringMasked everywhere, never logged, never sent to a package screen
field.urlstringschemes ('https', 'http'), hostPattern (regular expression for the host). A url used for egress needs a hostPattern. http is accepted on-prem only
field.numbernumbermin, max, step
field.booleanbooleannone
field.selectstringoptions (a list of { value, label, deployments? }), or optionsFrom (the name of an entry in options) with dependsOn (keys the list depends on)
field.multiselectlist of stringsSame as select, plus max
field.tagslist of stringsmaxItems, itemPattern, itemMaxLength. Cognipeer checks them every time the settings are saved
field.datestringnone
field.querystringlanguage, examples
field.explorerlist of targetsA tree or master-detail picker fed by a browse provider: browse, layout, levels, coverage, emptyMeans, maxSelection, widget
field.resourcestringkind: knowledge-base, dataset, config-ref or file
field.jsonanynone
field.customanywidget (a ui entry with slot field) and schema (a zod schema)

Patterns are checked at build time: a pattern, hostPattern or itemPattern that is not a valid regular expression fails the build.

ts
const settings = {
  serverUrl: field.url({
    label: t('settings.serverUrl'),
    schemes: ['https'],
    hostPattern: '^[a-z0-9][a-z0-9.-]{0,252}$',
    required: true,
  }),
  readonly: field.boolean({ label: t('settings.readonly'), default: true }),
}
type Settings = ValuesOf<typeof settings> // import type { ValuesOf } from '@cognipeer/connector-sdk'

Conditions ​

A condition is data, not a function, because Cognipeer evaluates it without running your code. It is used by visibleWhen, when on auth methods, actions, sources and the MCP block.

ts
{ field: 'host', equals: 'github.com' }
{ field: 'host', in: ['ghe.com', 'server'] }
{ field: 'buckets', notEmpty: true }
{ all: [ /* conditions */ ] }
{ any: [ /* conditions */ ] }

when on an auth method, action, source or MCP block may name settings only. A condition that names an unknown field fails the build.

Settings versions ​

When a setting changes meaning, raise settingsVersion and add a migration. migrations is keyed by the target version. Cognipeer runs the function on upgrade, before the new code sees the settings.

ts
settingsVersion: 2,
migrations: { 2: (previous) => ({ ...previous, host: previous.host ?? 'github.com' }) },

Auth methods ​

auth lists the ways an account can sign in. Each method has an id (lower case letters, digits and -, up to 40 characters), a label, an optional when condition and a guide. Ids must be unique. The administrator picks one method when connecting.

KindBuilderCredential
api_keykit.auth.apiKeyFields the user types, stored sealed by Cognipeer
oauth2kit.auth.oauth2OAuth tokens, obtained, stored and renewed by Cognipeer
customkit.auth.customA session that your own authenticate function returns
nonekit.auth.noneNo credential: public access

In every method Cognipeer injects the credential into requests that go to the origin of http.baseUrl and to the origins in inject.origins. Other hosts get none. The package never sees the token or key.

guide is a guide id, or an object that picks one per deployment: { saas: 'oauth-saas', onprem: 'oauth-app' }. Every method has a guide, and every guide must exist in guides.

API key and token injection ​

ts
kit.auth.apiKey({
  id: 'pat',
  label: t('auth.pat'),
  fields: { token: field.secret({ label: t('auth.pat.token'), required: true }) },
  inject: { header: 'Authorization', scheme: 'Bearer', from: 'token' },
  guide: 'pat',
})

fields are the inputs of the connect form (any field kind). inject says where the value goes. It must hold exactly one of these kinds; an empty or unknown one fails the build.

injectMembersEffect
Headerheader, optional scheme ('Bearer' or 'Token'), from (the field that holds the value), optional originsSets the header. With scheme, the value is prefixed with it
Queryquery, from, optional originsAdds the value as a query parameter
Basicbasic: { username, password } (names of fields), optional originsSends HTTP Basic authentication
Database accountsql: { username, password }Cognipeer uses the fields to open database connections. Nothing is sent over HTTP
Mail accountmail: { username, password }Cognipeer uses the fields to sign in to the mail server
AWS Signature V4awsSigV4: { accessKeyId, secretAccessKey, sessionToken?, service: 's3', regionFromSettings }Cognipeer signs each request
Azure Shared KeyazureSharedKey: { accountFromSettings, key }Cognipeer signs each request
Azure SASazureSas: { from }Cognipeer appends the stored token to each request

The sql and mail kinds are valid only on an api_key method listed in sql.auth or mail.auth. The three signing kinds need http.profile; see Object storage. A signing inject has no origins: the signature goes to the origin of http.baseUrl only.

OAuth ​

kit.auth.oauth2 covers the sign-in where a user approves access at the vendor, and the server-to-server grants.

Options of the default grant, authorization_code:

OptionMeaning
endpoints{ authorize, token, revoke? }, or a function of the settings that returns them. revoke may contain {clientId}
scopesList sent as scope. An empty list sends none
scopeSeparatorSeparator of the scope list. Default a space
pkceUse PKCE if the vendor supports it
appWhose OAuth app, per deployment: { saas: 'customer', onprem: 'customer' }. See below
appFieldsThe clientId and clientSecret fields of the OAuth app
tokenRequestHow Cognipeer calls the token endpoint. See below
revocationHow Cognipeer calls the revoke endpoint. See below
captureFunction that turns the token response into non-secret values (tokens are removed first) that you can read as ctx.account.captured
injectWhere the access token goes, usually { header: 'Authorization', scheme: 'Bearer' }

app has two values. customer means the administrator registers an OAuth app at the vendor and enters it under OAuth apps in Cognipeer; the guide of the method must explain how, and can use {{redirectUri}} for the callback address Cognipeer shows. deployment means the app comes from the Cognipeer deployment's own configuration; it needs fixed endpoints (not a function of the settings). For a package you distribute yourself, use customer.

Cognipeer runs the whole flow: it keeps a state value for 10 minutes, exchanges the code, stores the tokens sealed, renews them before they end and revokes them on disconnect. If a request gets HTTP 401 with an account that has a refresh token, Cognipeer renews the token once and sends the same request again. Packages do nothing for this.

Token request and revocation members, all optional:

MemberValuesDefault
tokenRequest.clientAuthbody (client id and secret in the request) or basic (HTTP Basic)body
tokenRequest.bodyform or jsonform
tokenRequest.headersStatic extra headersnone
revocation.methodPOST or DELETEPOST
revocation.clientAuthbasic or bodybasic
revocation.bodyform or jsonform
revocation.tokenFieldBody key that holds the token, 1 to 64 letters, digits, _, ., -token
revocation.tokenaccess or refreshaccess
revocation.headersStatic extra headersnone

Static headers are never secrets. Names are HTTP header tokens of at most 64 characters, at most 8 headers, values printable ASCII of at most 256 characters. Authorization, Cookie, Set-Cookie, Host, Expect, hop-by-hop headers and every Proxy-* and Content-* header are refused at build time.

Server grants ​

Give oauth2 a grant of client_credentials or password when the service issues tokens to an application and no user signs in. There is no app, appFields or pkce; the connect form asks for the client id and secret (and a user name and password for password), and Cognipeer requests and renews the token. Use password only where the vendor documents it.

ts
kit.auth.oauth2({
  id: 'app-only',
  label: t('auth.appOnly'),
  grant: 'client_credentials',
  endpoints: { token: 'https://login.example.com/{tenantId}/oauth2/v2.0/token' },
  scopes: ['https://api.example.com/.default'],
  tokenRequest: { clientAuth: 'basic' },
  inject: { header: 'Authorization', scheme: 'Bearer' },
  guide: 'app-only',
})
OptionMeaning
endpoints{ token, revoke? }. token may contain {setting} placeholders in its path, filled from the connector's settings. A placeholder in the host part, or one that names no setting, fails the build
tokenParamsFixed extra token parameters such as audience. Never secrets
fieldsRelabel clientId, clientSecret, username and password. Cognipeer always asks for them and marks them required

An account is marked as needing a new sign-in when the vendor answers invalid_client or invalid_grant, or HTTP 401, to a token request.

Custom sign-in ​

kit.auth.custom takes fields and an authenticate(ctx, credentials) function that exchanges them for a session: { session: Record<string, string>, expiresInSec? }. This is the only code that sees the credentials. Cognipeer seals the session with the account and treats every session value as a secret. Other calls never see it: Cognipeer puts it on the requests that get the credential (auth on, to the origin of http.baseUrl or of inject.origins).

injectWhere the session goes
{ header, fromSession, scheme? }One session value as a header, after scheme when given
{ query, fromSession }One session value as a query parameter
{ body: { fromSession, encoding } }Values inside the request body, for APIs that want the session in the message (SOAP headers, JSON members)

Renewal. expiresInSec is a whole number of seconds from 1 to 30 days (other values are dropped). Cognipeer signs in again with the stored fields before a call when the session ends within two minutes, and before a request when it has ended. Without expiresInSec the session is kept until a reauthOn status. reauthOn lists HTTP statuses (400 to 599, at most 8): when a request that got the credential receives one, Cognipeer signs in again once and sends the request again once, with the same method, address and body, filled with the new session. A sign-in the vendor refuses (the hook throws AUTH_FAILED) marks the account as needing a new sign-in. A Cognipeer older than the one that introduced renewal keeps the first session until the account is connected again.

Session values in the body ​

inject: { body: { fromSession: ['user', 'token'], encoding: 'xml' } } lists 1 to 8 session keys (^[A-Za-z][A-Za-z0-9]{0,31}$) and the encoding of the body, xml or json. It belongs to custom methods only. The package writes sessionPlaceholder(key) (the text __cognipeer_session_<key>__) where a value belongs:

ts
import { sessionPlaceholder } from '@cognipeer/connector-sdk'

const envelope = (body: string) => `<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Header><Ticket xmlns="urn:example"><Token>${sessionPlaceholder('token')}</Token></Ticket></soap:Header>
  <soap:Body>${body}</soap:Body></soap:Envelope>`

Before a request leaves, Cognipeer replaces each placeholder with the value escaped for the encoding: xml escapes & < > " ' as entities (a value with characters XML 1.0 cannot carry is refused), json writes string escapes and accepts a placeholder only inside a JSON string. It refuses the request (POLICY_DENIED) when:

  • a placeholder is in the address, the query or a header, or in the body of a request that does not get the credential (auth: false, another origin, or a redirect hop to one);
  • the body is not UTF-8 of the method's encoding as its Content-Type says (text/xml, application/xml, application/*+xml; application/json, application/*+json; a charset other than UTF-8 or US-ASCII; no charset counts as UTF-8);
  • a placeholder names a key fromSession does not list, or one the session lacks;
  • the body would be larger than 32 MiB once the values are in.

Put placeholders only in element text or attribute values (XML) or inside strings (JSON). Cognipeer fills every placeholder it finds, so text from outside the package (a tool's input, a user's or a model's words, data read from the vendor) must not carry one into a body as it is: pass each such value through neutralizeSessionPlaceholders(escaped, encoding) after escaping it. It writes the first underscore of a placeholder as &#95; (XML) or \u005f (JSON), so the receiver reads the same text and Cognipeer no longer sees a placeholder. Run it on the whole text you build from several values, not on each part, when values sit next to each other.

ts
import { neutralizeSessionPlaceholders } from '@cognipeer/connector-sdk'

const text = (value: string) => neutralizeSessionPlaceholders(escapeXml(value), 'xml')

A body without placeholders goes out as it is. A Cognipeer that does not know body refuses the package at install: its manifest check fails closed on an inject kind it does not know, so set engines.console to a version that has it. The test host fills bodies in by the same rules and shows the placeholders, never the values, in host.http.requests.

Public access ​

kit.auth.none({ label, id?, deployments?, when?, guide? }) stores no credential and ctx.http sends none. The default id is public. Cognipeer still keeps an account record, so "connected" checks work. Offer it next to a credential method when the service has public data. A mail relay that needs no sign-in uses a none method with deployments: ['onprem'].

HTTP and permissions ​

ts
http: {
  baseUrl: (s) => `https://${s.region}.example.com/api`,
  headers: () => ({ Accept: 'application/json' }),
  timeoutMs: 20_000,
  maxResponseBytes: 5_000_000,
  retry: { attempts: 3, on: [502, 503, 504], respectRetryAfter: true },
  mapError,
},
permissions: { egress: { hosts: ['api.example.com'], fromSettings: ['serverUrl'] } },
http memberMeaning
baseUrlA string, or a function of the settings. Resolved when the settings are saved, an account connects or a token refreshes, and checked against egress
headersStatic headers sent with every request, or a function of the settings
timeoutMs, maxResponseBytesDefaults for requests: 30 000 ms and 10 MiB when absent
retry{ attempts, on, respectRetryAfter?, methods? }. See Runtime context
mapErrorTurns a vendor response into a ConnectorError. See Errors
readPost, graphqlPaths a read action may POST to. See Read actions
profile, methods, scopeObject storage rules. See Object storage

permissions.egress lists every host the package may call. It is shown on the install screen and enforced on every request, redirects included.

MemberMeaning
hostsExact host names or *.suffix. Wildcards are flagged on the install screen
fromSettingsKeys of url settings that hold a host the administrator enters. Each needs a hostPattern
fromCaptured[{ key, hosts }]: the host of a value captured at sign-in (such as an instance URL) is allowed when it matches one of hosts. Names only, not patterns
privateNetwork'onprem' allows private addresses for hosts the operator entered, when the operator's network allowance covers them. Never on SaaS. Default 'never'
caFromSettingsKey of a text setting, on-prem only, that holds PEM certificates for a private endpoint

permissions.tcp is a list of { fromSettings, ports?, portFromSettings?, privateNetwork? } for a server that Cognipeer reaches over TCP on the package's behalf, as the mail block does.

Database and mail blocks ​

sql and mail name the settings that hold the server. The values the administrator saves there are the only server the package can reach. The field requirements and limits are in Runtime context.

sql memberMeaning
enginesNon-empty list from postgres, mysql, mariadb, mssql, oracle. Cognipeer runs PostgreSQL, MySQL and MariaDB
engineFromSettingsKey of a select setting that holds the engine. Required when engines lists more than one
hostKey of a text setting. Required
port, database, caPem, schemasKeys of a number, text, text and tags setting. An empty port means the engine's default
tlsModeKey of a select setting whose values are among verify-full, verify-ca, skip-verify, disable. Offer the last two on-prem only
authIds of api_key methods whose inject is sql. Required
privateNetworknever (default) or onprem
limitsmaxRows, maxBytes, timeoutMs, poolMax; can only lower Cognipeer's limits
mail memberMeaning
host, security, fromAddressKeys of a text, select and text setting. Required. security values are among tls, starttls, plain, and plain is on-prem only
port, caPem, fromName, replyToKeys of a number, text, text and text setting. An empty port means the default of the security mode
allowedDomainsKey of a tags setting with the recipient domains. Empty means any
maxRecipientsKey of a number setting from 1 to 25
authIds of api_key methods whose inject is mail, or of none methods for a relay (on-prem only). Required
privateNetworknever (default) or onprem; the same value as the permissions.tcp entry
limitsmaxBodyBytes, maxRecipients; can only lower Cognipeer's limits

A package with a mail block also needs a permissions.tcp entry whose fromSettings is the mail host setting, with portFromSettings set to the mail port setting when there is one, or ports when there is not. cpc build rejects a key that names no setting or a setting of the wrong kind, unknown members and limits outside their maximum.

Actions ​

An action is one tool. The key in actions is the tool name the model sees: lower case letters, digits and _, starting with a letter, up to 64 characters.

ts
const getRepo = kit.action({
  title: t('actions.get_repo'),
  description: 'Get one repository: description, default branch, visibility and counts.',
  access: 'read',
  input: z.object({ owner: z.string().min(1).max(100), repo: z.string().min(1).max(100) }),
  pinnable: ['owner', 'repo'],
  async run(ctx, input) {
    return ctx.http.get(p`/repos/${input.owner}/${input.repo}`)
  },
})
MemberRequiredMeaning
titleyesDisplay name
descriptionyesEnglish text for the model, at most 1024 characters. Be specific: it decides when the model uses the tool
accessyesread, write or destructive
inputyesA zod object schema. Must be an object, and inlined (no $ref). Cognipeer shows the schema to the model
outputnoA zod schema of the result
whennoA condition on settings. The action is offered only while it holds
pinnablenoInput keys an administrator may pin or constrain per connector
nodenoHow the action looks as a node in the Flow editor. See Flow nodes
approvalnoAccepted and ignored. Approval is decided per agent, not by the connector
run(ctx, input)yesThe implementation. Returns the result

Access ​

access describes what the action does. Cognipeer turns it into the standard tool markings and does two things with it.

accessMarking on the toolWhat Cognipeer does
readread-onlyAgents run the tool without asking. Cognipeer enforces it on the request itself, see Read actions
writechanges data, not destructiveThe tool asks for approval by default
destructivechanges data, destructiveThe tool asks for approval by default

The connector never decides whether a call asks. The agent owner sets that on the agent's tool settings, where a tool can be set to Never ask. A tool with no marking, or an unknown access, counts as destructive. See Tool approvals.

Mark an action write or destructive whenever it changes anything, including a send. Mark an action that only shows what would happen, such as a draft, as read, so an agent can use it without asking.

Read actions ​

A read action may send only GET and HEAD. Two members of http open narrow exceptions, and Cognipeer checks them on every request and every redirect hop:

MemberWhat a read action may do
http.readPostPOST to the listed paths, whatever the body. For search endpoints that carry the query in the body
http.graphqlPOST to the listed paths, or GET with a query parameter, only when the request holds queries. Mutations and subscriptions are refused

A path is relative to baseUrl and is one of:

  • exact, such as /search;
  • with * as a whole segment that is not the last, matching exactly one non-empty segment, such as /workspaces/*/search/code;
  • ending in * or prefix*, matching anything below the prefix, such as /data_sources/*.

A pattern starts with /, has at most 200 characters and 16 segments, and a list holds at most 200 patterns. A request path with //, a dot segment, an encoded slash (%2F) or backslash, or ; never matches. Prefer the whole-segment form to a trailing prefix: it grants one endpoint instead of everything below. For a GraphQL path the body must be JSON of at most 256 KiB, with the query text at most 100 000 characters; write actions are not checked. cpc build validates both lists.

Flow nodes ​

Every action can be a node in the Flow editor. Nothing has to be declared: Cognipeer derives the node form from the action's input schema. Add a node block only to improve it. The member is optional and ignored by a Cognipeer that does not know it.

ts
const searchDocuments = kit.action({
  title: t('actions.search_documents'),
  access: 'read',
  input: z.object({ text: z.string(), type: z.string().optional() }),
  node: {
    summary: t('nodes.search_documents.summary'),
    group: t('nodes.group.documents'),
    params: { type: { label: t('nodes.type'), help: t('nodes.type.help'), optionsFrom: 'documentTypes', advanced: true } },
    order: ['text', 'type'],
    outputExample: { documents: [{ id: 'doc-1', title: 'SOP' }] },
  },
  // …
})
MemberRule
summary, groupMessages. group is the heading of the action under the package's name in the palette
paramsKeys are properties of the action's input. Per key: label, help (messages), placeholder (text, at most 200 characters), kind, optionsFrom, dependsOn, visibleWhen, advanced
params.<key>.kindOne of text, textarea, number, boolean, select, multiselect, date, url, tags, json
params.<key>.optionsFromA key of options; only with kind select or multiselect. The list is read only while the connector has a working account; without one the field takes a typed value
params.<key>.dependsOnInput keys or settings keys
params.<key>.visibleWhenA condition over input keys (the build refuses a name that is not an input). The editor shows the field by it for one input with equals, in or notEmpty, or an any of equals or in conditions on one input; any other shape is ignored and the field is always shown
orderInput keys, each at most once
outputExampleAny JSON, at most 64 KiB. The editor shows it as the output picker before the node has run
hiddenBoolean: do not offer the action as a node

The palette lists a package's nodes under the package's name. An action whose when condition (over the connector's settings) is false for every active connector of the package is not offered as a node, as it is not offered to an agent as a tool, and the node's connector choice lists only the connectors that have it on.

The form is derived from input like this (deriveNodeForm in the SDK is the reference):

SchemaKind
string with enumselect
string with format date or date-timedate
string with format uriurl
string with maxLength above 500textarea
other stringtext
number, integernumber (min, max)
booleanboolean
array of string enummultiselect
array of string or numbertags
anything elsejson

MCP server ​

If the service runs an official remote MCP server, point at it. Cognipeer connects with the account's credential and offers the server's tools instead of the package's own actions (one tool per connector).

MemberMeaning
urlStreamable HTTP endpoint: a string, or a function of the settings
headersExtra request headers, for example a toolset selection. A string map or a function of the settings
authId or ids of the auth methods whose credential is sent
whenA condition on settings
tools{ include?, exclude?, access? }. access maps tool names or patterns to read, write or destructive. Tools that match no pattern count as destructive
beforeCallFunction that runs in the package before each MCP tool call and may rewrite the arguments

A tool keeps the markings the MCP server sent; the package's access patterns can make a tool stricter but never looser. The URL is checked against egress.

Sources ​

A source lists items for Knowledge Engine and keeps them in step with the service.

MemberMeaning
titleDisplay name
outputdocuments or records
filtersFields of the source form (same field kinds as settings)
schedule{ default, minIntervalMin? }
incrementalThe source can continue from a checkpoint
deletesprune, events or none
aclThe source reports access lists
guideId of a guide shown beside the source form
sync(ctx, run)An async generator that yields changes

Yield changes with the change helper: change.upsert(item), change.delete(id), change.skip(id, reason?), change.checkpoint(cursor, { scope? }), change.scopeComplete(scope?), change.progress({ done, total, message }) and change.record. Cognipeer pulls one change at a time and the generator stays paused at each yield until Cognipeer has handled it, so a file's data() can still use ctx.

RuleValue
Item idat most 512 characters
Item titlecut at 500 characters
Item urldropped above 2048 characters
Progress messagecut at 500 characters
Checkpoint cursorat most 64 KB of JSON, else the call fails with POLICY_DENIED
File sizeat most 20 MB; a larger file is skipped

Report deletions only when a listing is complete (scopeComplete); never prune after a partial or failed listing. Stop at run.deadline after a checkpoint, and Cognipeer starts the next segment from it with resumed: true.

Triggers ​

triggers lets an event in the service start an agent run or a flow. Cognipeer owns the hard parts (the public URL, the signing secret, the schedule, the cursor and de-duplication); the package says how to read the service's payload and, optionally, how to register the webhook for the user. Each entry is keyed by a name matching ^[a-z][a-z0-9_]{0,63}$. A package with triggers needs engines.console of >=1.22.0; an older Cognipeer ignores the member. Texts are messages, like everywhere else. The build refuses an entry that breaks a rule below and any unknown member.

There are two kinds:

  • webhook: the service calls Cognipeer. Cognipeer verifies the signature over the raw bytes before any package code runs, so the package never does. parse turns a verified delivery into events.
  • poll: Cognipeer calls the package on a cron schedule, and the package returns what happened since the last cursor.
ts
triggers: {
  document_events: kit.trigger({
    kind: 'webhook',
    title: t('triggers.document_events.title'),
    description: t('triggers.document_events.description'),
    params: { type: field.select({ label: t('triggers.document_events.type'), optionsFrom: 'documentTypes' }) },
    events: [{ type: 'document.created', title: t('triggers.document_events.event.created') }],
    eventSchema: z.object({ documentId: z.string(), title: z.string() }),
    sample: { type: 'document.created', data: { documentId: 'doc-1', title: 'SOP' } },
    webhook: {
      verify: { scheme: 'hmac', algorithm: 'sha256', header: 'X-Acme-Signature', prefix: 'sha256=', encoding: 'hex' },
      eventType: { header: 'X-Acme-Event' },
      deliveryId: { header: 'X-Acme-Delivery' },
      ping: { header: 'X-Acme-Event', values: ['ping'] },
      headers: ['x-acme-event'],
      parse(ctx, delivery, params) { return [{ id: delivery.deliveryId!, type: 'document.created', data: { documentId: '…', title: '…' } }] },
      subscribe: {
        requires: { scopes: ['webhooks.write'], help: t('triggers.document_events.requires') },
        async create(ctx, { params, callbackUrl, secret, events }) { /* register at the service */ return { remoteId: '…' } },
        async remove(ctx, { remoteId }) { /* remove it */ },
      },
      setup: t('triggers.document_events.setup'),
    },
  }),
  audit_events: kit.trigger({
    kind: 'poll', title: t('…'), description: t('…'), events: [ /* … */ ],
    poll: {
      schedule: { default: '*/10 * * * *', minIntervalMin: 5 },
      async run(ctx, { params, cursor, first }) { return { events: [], cursor: cursor ?? 'start' } },
    },
  }),
}
MemberRule
title, descriptionRequired messages
kindwebhook or poll. A webhook block only with webhook, a poll block only with poll
paramsThe form of the trigger on the agent (the repository to watch, a project). Fields as for settings, never secret. References (optionsFrom, visibleWhen, dependsOn) may name the trigger's own params and the connector's settings. An optionsFrom list is read only while the connector has a working account; without one the field takes a typed value
events1 to 100. type is unique and matches ^[A-Za-z0-9._:-]{1,64}$; title is a message. These are the vocabulary of the agent's event allow-list
eventSchemaOptional JSON Schema of an event's data: an object schema without $ref. Feeds the filter and prompt pickers
sampleOptional { type, data }. type is one of events, data an object; the whole sample is at most 64 KiB. Feeds the trigger's test button
webhook.verifyscheme is one of the five below. Any other member or scheme fails the build
webhook.eventType, deliveryId{ header?, path? }, at least one. path is dotted (a.b.c; no __proto__, constructor or prototype). Headers in lowercase. A header is never one that carries the secret or its proof
webhook.ping{ header?, path?, values }, 1 to 20 values; the same header rule. A delivery that matches is answered 200 and dispatches nothing
webhook.headersAt most 20 unique lowercase header names handed to parse with the delivery. Never authorization, proxy-authorization, cookie, set-cookie, x-api-key, nor a header verify reads: its header, its timestampHeader, and with standard-webhooks all of webhook-id, webhook-timestamp and webhook-signature
webhook.parseThe parse hook. Without one, a delivery is one event: id from deliveryId (else a hash of the body), type from eventType (else the first declared event), the JSON body as data
webhook.subscribePresent when the package has create and remove hooks. requires.scopes (at most 20, any one is enough) is a hint, requires.help a message. Cognipeer does not check it: a failed subscribe falls back to manual setup
webhook.setupRequired message with the manual steps. Cognipeer fills {url} and {secret} in
poll.scheduledefault a valid five-field cron (numbers, lists, ranges, steps, month and weekday names; not L, W, # or ?) and minIntervalMin an integer from 1 to 1440. The shortest gap the default produces must not be below minIntervalMin

The SDK writes every header name in lowercase, whatever case the definition used. A header named by eventType, deliveryId or ping reaches the package, the delivery log and the run, so it cannot carry the secret or its proof: the build refuses authorization, proxy-authorization, cookie, set-cookie, x-api-key, the header verify reads, and webhook-signature when the scheme is standard-webhooks. For eventType, deliveryId and ping, webhook-id, webhook-timestamp and the timestampHeader of a signed hmac are no secret and stay allowed (unlike in webhook.headers, above); a body path is always allowed.

Verifying a webhook ​

webhook.verify is a closed set. Cognipeer runs it over the raw request bytes before any package code and compares digests in constant time. A failure names the problem (missing_header, bad_format, bad_signature, expired, no_secret) and never a value. verifyWebhookSignature and signWebhookPayload are exported for tests.

schemeThe service sendsMembers
hmac<prefix><signature> in header: the HMAC of the body (or of <timestamp>.<body>) with the secret as the keyalgorithm (sha256, sha1), header, encoding (hex, base64), prefix?, signed? (body, timestamp.body), timestampHeader?, toleranceSec? (default 300)
tokenThe secret itself in headerheader
basicAuthorization: Basic base64(<user>:<secret>), the user ignorednone
bearerAuthorization: Bearer <secret>none
standard-webhookswebhook-id, webhook-timestamp and webhook-signature (v1,<base64>) with whsec_ + base64 as the key, within 300 secondsnone

timestampHeader and toleranceSec exist only with signed: 'timestamp.body', which requires timestampHeader (epoch seconds).

Events ​

An event is { id, type, occurredAt?, data, summary? }. id (1 to 200 characters) is the de-duplication key: the same id is the same event, so use the service's own event id and not a timestamp. type is 1 to 64 characters. data is a JSON object of at most 256 KiB; the agent's filters and prompt variables read it, so flatten what a user would filter on. occurredAt, when given, is an ISO 8601 time. summary is one line of at most 500 characters for run lists. Other members are dropped.

Trigger operations ​

A package with triggers answers four more call operations. Each answer is checked against the trigger limits before it leaves the package. A malformed answer fails with UPSTREAM: not an object, an event without a valid id, type, occurredAt or summary, a remoteId of the wrong length, a poll without a cursor. An answer over a count or size limit (the number of events, an event's data, the cursor, meta) fails with POLICY_DENIED. The hooks are listed in runtime.hooks as trigger.<name>.parse, .subscribe, .unsubscribe (webhook) and .poll (poll).

OperationAccessGetsReturns
trigger.parsereaddelivery: { headers, body, eventType?, deliveryId? }, with only the headers the trigger lists{ events }, at most 50. [] ignores the delivery
trigger.subscribewritecallbackUrl (https; http only for loopback or an on-premises deployment), secret, events{ remoteId, meta? }: remoteId 1 to 200 characters, meta an object of at most 4 KiB
trigger.unsubscribewriteremoteId, meta?{}. A NOT_FOUND from the vendor counts as success, so a webhook the user already deleted does not block removing the trigger
trigger.pollreadcursor (null on the baseline), first{ events, cursor, more? }: at most 100 events, cursor any JSON except null and at most 64 KiB, on every answer including the baseline

parse and poll run with read access: ctx.http can only read there, so a parse that fetches the full object is fine and one that writes fails with POLICY_DENIED. subscribe and unsubscribe run with write access.

The signing secret. The package never receives it. create gets secret set to the placeholder __cognipeer_trigger_secret__; put it where the service wants a secret. While the call runs, Cognipeer replaces the placeholder in the header values and the JSON or text bodies of the http requests the package makes, and nowhere else. Return the service's id as remoteId, and anything remove needs in meta.

The baseline. poll with first: true and no cursor returns the service's current high-water mark (the id of the newest record, or the time when there is none) as cursor. Cognipeer ignores the events of that answer, so enabling a poll never replays history. Cognipeer sends first: true whenever it holds no cursor for the poll: for a new poll, after the connector, the trigger or its parameters change, and after every agent trigger on the poll was switched off at a scheduled check. After that, return the events since cursor, oldest first, and the cursor to continue from, and make a repeated call safe: Cognipeer de-duplicates by event id. With more: true Cognipeer calls again right away with the new cursor (a page was full); leave it out when you have caught up.

Without subscribe the user connects the account and pastes the URL and secret into the service by hand, following setup. With it, Cognipeer registers the webhook when the account allows and falls back to the manual steps when it does not.

Guides ​

A guide is Markdown that Cognipeer shows to the administrator while connecting. Declare it with guide(path, options) and write one file per locale.

ts
guides: {
  pat: guide('./guides/pat', { audience: 'admin' }),
  'network-onprem': guide('./guides/network-onprem', { audience: 'operator', deployments: ['onprem'] }),
}
  • guide('./guides/pat') reads guides/pat.en.md and guides/pat.tr.md. Both are required.
  • audience is operator or admin. deployments limits where the guide is shown.
  • {{redirectUri}} in the text is replaced with the connector's OAuth callback URL.
  • Cognipeer renders the Markdown without raw HTML.
  • Every auth method and every on-prem network need has a guide. Name UI labels exactly as they appear in the messages.

Assets ​

assets/ holds the icon and any other file the package needs, as SVG or PNG. The icon member points at one of them. File names use letters, digits, ., _ and -, and the package may contain only files with the extensions json, mjs, js, map, md, svg, png, txt and sha256.

Package screens ​

ui declares React screens that Cognipeer renders in a sandboxed frame. ui entries use lower-kebab-case ids and take slot (field, settings, account, source.filters, tab or item.preview), entry, and optional for, title, rpc, browse and access. A screen may call only the rpc methods and browse providers it lists. cpc build bundles each entry into ui/<id>.js; the bundle is at most 1 MB. The components and hooks are in @cognipeer/connector-ui.

Studio · Pulse · Console · Agent SDK and more — the Cognipeer documentation hub · Contact Support