ai-catalog-sdk

mcp
Guvenlik Denetimi
Basarisiz
Health Uyari
  • License — License: Apache-2.0
  • Description — Repository has a description
  • Active repo — Last push 0 days ago
  • Low visibility — Only 5 GitHub stars
Code Basarisiz
  • process.env — Environment variable access in .github/workflows/release.yml
  • network request — Outbound network request in scripts/browser/smoke.js
  • crypto private key — Private key handling in scripts/browser/smoke.js
  • spawnSync — Synchronous process spawning in scripts/smoke-browser.mjs
  • process.env — Environment variable access in scripts/smoke-browser.mjs
  • network request — Outbound network request in scripts/smoke-browser.mjs
  • crypto private key — Private key handling in scripts/smoke-browser.mjs
  • spawnSync — Synchronous process spawning in scripts/smoke-package.mjs
  • process.env — Environment variable access in scripts/smoke-package.mjs
  • crypto private key — Private key handling in scripts/smoke-package.mjs
Permissions Gecti
  • Permissions — No dangerous permissions requested

Bu listing icin henuz AI raporu yok.

SUMMARY

AI Catalog TypeScript SDK

README.md

ai-catalog-sdk

Discover, parse, validate, and author JSON-native AI Catalog documents in TypeScript for Node.js and browsers.

Parse a catalog

import {
  entryTypes,
  isEntryType,
  parseCatalogJson,
} from 'ai-catalog-sdk';

const source = `{
  "specVersion": "0.9",
  "entries": [
    {
      "identifier": "example-agent-plugin",
      "type": "application/agent-plugins+zip",
      "url": "https://example.com/example-agent-plugin.zip"
    },
    {
      "identifier": "example-catalog",
      "type": "application/ai-catalog+json",
      "url": "https://example.com/catalog.json"
    }
  ]
}`;

const catalog = parseCatalogJson(source);
const pluginEntries = catalog.entries.filter(
  isEntryType(entryTypes.agentPlugin),
);

The parsed result is an ordinary mutable, JSON-shaped object. Parsing checks field shapes and primitive types while preserving declaration values and unknown JSON-valued properties. It does not fetch or parse referenced artifacts.

Parsing does not verify trust

Parsing provides structurally usable data, including declarations that may fail authoring validation or verification. Use authoring validation to check an assembled document’s declarations and consistency, and verification to evaluate its artifacts and endorsements.

Handle invalid input

Use a safe parser when validation failures are expected and should be handled as values:

import { safeParseCatalogJson } from 'ai-catalog-sdk';

function parseCatalogInput(source: string) {
  const result = safeParseCatalogJson(source);

  if (result.success) {
    return result.data;
  }

  for (const issue of result.error.issues) {
    console.error({
      code: issue.code, // Example: "invalid_value"
      path: issue.path, // Example: ["entries", 0]
      message: issue.message,
    });
  }

  return undefined;
}

Use code to classify an issue and path to locate it in the input. Present message to users, but do not branch on its exact wording.

See Validation diagnostics for diagnostic codes and handling guidance.

Discover a website's catalog

Pass an absolute HTTPS website URL to discoverCatalog():

import { discoverCatalog } from 'ai-catalog-sdk';

const result = await discoverCatalog('https://example.com/tools');

if (result.status === 'found') {
  console.log(result.url, result.catalog.entries);
}
Status Meaning
not_found No catalog was found at the checked well-known locations.
invalid_catalog The retrieved content could not be parsed as a catalog. url identifies the catalog response; error is a CatalogParseError with path-specific issues.
fetch_failed The website or catalog request failed. Includes url and an error explaining the failure.

Discovery follows website redirects, then checks the final response for an HTTP Link with rel="ai-catalog". If no catalog link is advertised, it tries /.well-known/ai-catalog.json at the website's origin. When the website redirects to a different origin, it tries the destination origin first, then the original origin if needed. A selected HTTP link takes precedence: if its catalog cannot be fetched or parsed, discovery returns that failure without trying the well-known locations. HTML <link> elements are not inspected, so catalogs advertised only in HTML will not be discovered.

In browsers, discovery is subject to CORS, and cross-origin websites must permit JavaScript to read their Link header for the SDK to find a catalog link. See Configure portable network access for browser requirements and optional application-wide header checking.

To use a domain's well-known catalog without requesting the website or inspecting its HTTP Link header, pass { strategy: 'well-known' }. This requests /.well-known/ai-catalog.json only at the input URL's origin.

A found result contains the parsed catalog and the URL it was retrieved from after any redirects. The catalog remains unverified; apply the verification utilities when your application needs artifact or endorsement checks. Discovery does not traverse nested catalogs or fetch referenced artifacts.

Load a catalog from an entry

Use loadCatalogFromEntry() to load one entry with type application/ai-catalog+json. For example, select a nested catalog from a discovered catalog:

import {
  discoverCatalog,
  entryTypes,
  isEntryType,
  loadCatalogFromEntry,
} from 'ai-catalog-sdk';

const discovered = await discoverCatalog('https://example.com/tools');

if (discovered.status === 'found') {
  const entry = discovered.catalog.entries.find(isEntryType(entryTypes.aiCatalog));

  if (entry) {
    const loaded = await loadCatalogFromEntry(entry, { baseUrl: discovered.url });

    if (loaded.status === 'found') {
      console.log(loaded.catalog.entries);
    }
  }
}

For a URL entry, the loader retrieves and parses the referenced catalog over HTTPS. A found result includes catalog, the final response url, and the decoded response bytes.

For an inline entry, the loader parses entry.data as the complete catalog. A found result includes catalog and, when baseUrl was supplied, the same value as url. It has no response bytes.

To support relative URLs, pass the containing catalog's final response URL as baseUrl, as above. Use a successful load's returned url as the base for loading its entries. An inline catalog's url carries inherited resolution context; it does not identify a separately retrieved catalog. Without a base URL, a relative reference returns fetch_failed.

If catalog parsing fails, the result has status invalid_catalog and a CatalogParseError in error. For a URL entry, the result also includes url. URL resolution or retrieval failures return fetch_failed with url and error. Malformed entry arguments, entries of another type, and invalid options reject with TypeError.

Loading performs ordinary structural parsing, without authoring validation, verification, or automatic traversal. For a URL entry, pass the returned bytes to checkCatalogEntry(entry, loaded.bytes) when your application needs artifact and endorsement checks. For an inline entry, use checkCatalogEntry(entry) instead. Interpret those reports as described in Check a catalog entry.

Check a catalog signature

checkCatalogSignature() checks one catalog snapshot with a public key and expected algorithm selected by the caller:

import { checkCatalogSignature } from 'ai-catalog-sdk';

const result = await checkCatalogSignature(catalog, {
  publicKey,
  expectedAlgorithm: 'ES256',
});

if (result.status !== 'valid') {
  throw new Error(`Catalog signature check failed: ${result.status}`);
}

A valid result means the exact caller-selected key verified the signature over the exact canonical catalog snapshot captured by this invocation. It does not authenticate the key as belonging to the catalog operator, verify entry Trust Manifests or artifacts referenced by URLs, establish freshness, or decide trust. See Verification utilities for failure details and the complete boundary.

Check a catalog entry

checkCatalogEntry() checks an entry's fields and declared artifact digest, then evaluates each selected Trust Manifest independently. A malformed selected manifest receives invalid_manifest without preventing the other manifests from being checked. For the did-web-v1 profile, it resolves the contributor's current DID document and selects an authorized assertion key:

import { checkCatalogEntry } from 'ai-catalog-sdk';

const report = await checkCatalogEntry(entryWithUrl, artifactBytes);

if (report.status !== 'checked') {
  throw new Error(`Entry check failed: ${report.status}`);
}

const publisherEndorsements = report.manifests.filter(
  result => result.status === 'passed' && result.isPublisherEndorsement,
);

For an entry with url, supply the artifact bytes obtained by your application. For an entry with data, call checkCatalogEntry(entryWithData); the SDK canonicalizes the inline artifact with JCS.

checked means the requested checks completed. Each attached manifest has its own result in the original array order; manifests excluded by the contributor options receive not_checked. The report may contain no manifests or no passing endorsements. A passed manifest result authenticates its contributor, binds its claims to the entry and artifact, and checks its time window. isPublisherEndorsement: true additionally establishes the did:web Publisher Profile's exact relationship to the entry's urn:air namespace. Applications choose which contributors and endorsements they require. See Verification utilities for filtering, results, and network controls.

Check a Trust Manifest with a supplied key

Use checkCatalogEntryTrustManifest() when your application supplies the verification key, such as when implementing a different signer profile:

import { checkCatalogEntryTrustManifest } from 'ai-catalog-sdk';

const result = await checkCatalogEntryTrustManifest(
  entryWithUrl,
  artifactBytes,
  manifest,
  { publicKey, expectedAlgorithm: 'ES256' },
);

For an entry with data, omit artifactBytes. The function validates the entry's fields and the explicit manifest, ignoring the entry's attached trustManifests. A passed result means the manifest’s declarations and signature pass the supplied-key checks, its subject matches the entry and artifact, and its time window passes. The caller is responsible for selecting and applying the signer profile and authenticating and authorizing the key; the function performs no network requests. See Verification utilities for details.

Author a catalog

Catalogs are ordinary JSON-shaped objects. Use satisfies AICatalog to check known fields at compile time, call assertValidCatalog() to validate the assembled document, and serialize it with JSON.stringify():

import {
  mediaTypes,
  assertValidCatalog,
  type AICatalog,
} from 'ai-catalog-sdk';

const catalog = {
  specVersion: '0.9',
  entries: [
    {
      identifier: 'example-agent-plugin',
      type: mediaTypes.agentPluginZip,
      url: 'https://example.com/example-agent-plugin.zip',
    },
  ],
} satisfies AICatalog;

assertValidCatalog(catalog);
const json = JSON.stringify(catalog, null, 2);

The assertion checks declaration formats and internal consistency, including entry uniqueness and whether attached manifests describe their containing entries. It returns no value and throws CatalogValidationError with path-specific issues on failure. Unsigned catalogs are allowed. Artifact integrity, cryptographic authenticity, and current endorsement acceptance are evaluated by the verification utilities.

Sign a Trust Manifest

To add a signed endorsement, declare the entry's artifact digest, sign a Trust Manifest, and attach the result to trustManifests before serializing the catalog. This example reads the artifact from a local file and uses your configured privateKey with the separately installed jose package:

import { readFile } from 'node:fs/promises';
import { CompactSign } from 'jose';
import {
  assertValidCatalog,
  createDigest,
  mediaTypes,
  signTrustManifest,
  type AICatalog,
} from 'ai-catalog-sdk';

const artifactBytes = await readFile('example-agent-plugin.zip');
const entry = {
  identifier: 'urn:air:example.com:agent:example-plugin',
  type: mediaTypes.agentPluginZip,
  url: 'https://example.com/example-agent-plugin.zip',
  digest: await createDigest(artifactBytes),
};

const manifest = await signTrustManifest(
  entry,
  { contributor: 'did:web:example.com' },
  ({ payload, typ }) => new CompactSign(payload)
    .setProtectedHeader({ alg: 'ES256', typ, kid: 'did:web:example.com#release-key' })
    .sign(privateKey),
);

const catalogWithEndorsement = {
  specVersion: '0.9',
  entries: [{ ...entry, trustManifests: [manifest] }],
} satisfies AICatalog;

assertValidCatalog(catalogWithEndorsement);
const jsonWithEndorsement = JSON.stringify(catalogWithEndorsement, null, 2);

The digest must describe the exact bytes published at entry.url. For an inline entry, use createDigest(entry.data) to hash its JCS-canonicalized JSON value. The signed Trust Manifest endorses the entry's artifact; the containing catalog remains unsigned. See Signing for signing with an explicit subject and supported callback formats.

Choose an API

The ai-catalog-sdk entry point provides the same APIs in Node.js and browsers.

Task API Import path
Parse catalog JSON text parseCatalogJson() or safeParseCatalogJson() ai-catalog-sdk
Parse a catalog from an existing JSON value parseCatalog() or safeParseCatalog() ai-catalog-sdk
Parse one catalog entry from an existing JSON value parseCatalogEntry() or safeParseCatalogEntry() ai-catalog-sdk
Discover a catalog from a website URL discoverCatalog() ai-catalog-sdk
Load the catalog represented by an entry loadCatalogFromEntry() ai-catalog-sdk
Check a catalog signature with a supplied public key checkCatalogSignature() ai-catalog-sdk
Check an entry and its selected endorsements checkCatalogEntry() ai-catalog-sdk
Check one explicit Trust Manifest against an entry with a supplied public key checkCatalogEntryTrustManifest() ai-catalog-sdk
Validate an assembled catalog before serialization assertValidCatalog() ai-catalog-sdk
Compose structural validation with Zod aiCatalogSchema, catalogEntrySchema, or trustManifestSchema ai-catalog-sdk/zod
Use JSON Schema in TypeScript or JavaScript aiCatalogJsonSchema ai-catalog-sdk/json-schema
Use raw JSON Schema with another validator or tool ai-catalog.schema.json ai-catalog-sdk/schema/ai-catalog.schema.json

The parse* functions throw CatalogParseError when input is invalid. The matching safeParse* functions return a discriminated ParseResult instead. All SDK parsers apply defensive input validation that the standalone schemas do not. See What gets validated for the parsing, authoring, and schema boundaries.

Use lower-level verification utilities

Use the individual utilities when the composed catalog-entry check does not fit your workflow:

API Use it for Important boundary
canonicalizeJsonValueToBytes() Encoding a logical JSON value as RFC 8785 JCS UTF-8 bytes Accepts an already-materialized JSON value, not JSON source text
createCatalogSignaturePayload() Creating the canonical detached-JWS payload for an AI Catalog Does not validate the catalog, construct or verify a JWS, fetch URL artifacts, or establish trust
createTrustManifestSignaturePayload() Creating the canonical detached-JWS payload for a Trust Manifest Does not validate the manifest, construct or verify a JWS, or establish trust
checkTrustManifestSignature() Checking a manifest snapshot with one caller-selected public key and expected algorithm Currently supports ES256; does not check the subject digest, identity, freshness, or trust
checkDigest() Comparing exact bytes or JCS-canonicalized JSON with a declared digest Currently supports sha256, sha384, and sha512

These utilities do not fetch content or resolve keys. See Verification utilities for their inputs, results, errors, security boundaries, and examples.

Schemas

Use the Zod schemas to compose AI Catalog validation in TypeScript. The package also provides a JSON Schema for other validators and tools. It follows the 2020-12 version of the JSON Schema standard. This SDK maintains the schema as an interpretation of the pinned AI Catalog specification; it is not the official AI Catalog schema definition.

import { aiCatalogSchema } from 'ai-catalog-sdk/zod';
import { aiCatalogJsonSchema } from 'ai-catalog-sdk/json-schema';

Modern Node ESM consumers can import the raw artifact with a JSON import attribute:

import schema from 'ai-catalog-sdk/schema/ai-catalog.schema.json' with { type: 'json' };

TypeScript NodeNext consumers also need compilerOptions.resolveJsonModule: true for the raw JSON import. Importing aiCatalogJsonSchema from ai-catalog-sdk/json-schema avoids that configuration.

What gets validated

  • The parse* and safeParse* functions check known field shapes and primitive types and reject non-JSON or excessively large or deeply nested inputs. Catalog parsers accept 0.x and 1.x values of specVersion and preserve the declared value. Declaration formats, ranges, and relationships are preserved for explicit validation. For example, a timestamp string such as "yesterday" is retained, while a number in that field fails parsing.
  • assertValidCatalog() checks an assembled catalog’s declaration formats, constraints, and relationships, including entry uniqueness, subject/entry correspondence, signer/contributor equality, and timestamp ordering. It also checks digest declarations, signature representations and signed-payload eligibility, and locally checkable requirements of supported signer profiles. Unfamiliar but well-formed profiles and algorithms do not fail solely because the SDK cannot verify them.
  • The Zod schemas validate their declared structure and constraints with native Zod errors and behavior. They do not apply the root parsers’ defensive input limits or the complete authoring assertion’s checks.
  • The JSON Schema describes portable document constraints. Format enforcement depends on the validator; use assertValidCatalog() for the document relationships and signature/payload checks described above.

The SDK targets AI Catalog v0.9, the v1.0 release candidate, at an exact specification snapshot. See Specification snapshot interpretation for the pinned revision and how conflicts in that snapshot are handled.

Configure portable network access

By default, discovery can select different catalogs in Node.js and browsers. A browser application fetching from another origin may be able to read the response’s status and body without being allowed to read its HTTP Link header.

For example, a website might return Link: </tools/catalog.json>; rel="ai-catalog" with Access-Control-Allow-Origin: *, but no Access-Control-Expose-Headers. The SDK in Node.js requests /tools/catalog.json, while in a browser it tries /.well-known/ai-catalog.json. Those URLs can serve different catalogs.

To check for these browser permissions while running in Node.js, enable requirePublicAccessHeaders once at startup:

import { configure } from 'ai-catalog-sdk';

configure({ requirePublicAccessHeaders: true });

This setting applies to discovery, catalog loading, and automatic DID resolution, including their nested requests. Each invocation captures the setting when it starts.

With requirePublicAccessHeaders enabled, missing required headers are treated as retrieval failures: fetch_failed for discovery and loading, or issuer_check_failed for DID resolution.

Servers can satisfy the contract with these headers on their final responses:

Access-Control-Allow-Origin: *
Access-Control-Expose-Headers: Access-Control-Allow-Origin, Access-Control-Expose-Headers, Link

Alternatively, use Access-Control-Expose-Headers: * in place of the explicit header list.

The Link entry lets discovery check the Link header, including to confirm when a catalog link is not provided.

Exposing the two access-control headers lets the SDK check the same declarations in both environments. The check applies even to same-origin requests and error responses. When discovery would otherwise return not_found, missing required headers produce fetch_failed instead.

When following redirects with requirePublicAccessHeaders enabled, the SDK in Node.js stops retrieval if any redirect response lacks Access-Control-Allow-Origin: *, though only the final response needs the Access-Control-Expose-Headers declaration shown above. Browsers follow redirects under their own permission rules and may accept a redirect that the SDK rejects in Node.js—for example, one that permits only the application's origin.

Requirements

  • Node.js >=22.20.0, or a modern browser in a secure context with Fetch and Web Crypto
  • ES modules only
  • TypeScript >=5.5 for typed consumers
  • Zod ^4.6.6 as a peer dependency

Development

See Contributing for development setup, checks, schema generation, and documentation guidance.

Yorumlar (0)

Sonuc bulunamadi