Sign in

CosmosClient Reference

Main SDK client — authentication, configuration, sub-managers, and convenience methods

sdktypescriptclientreference

Updated 2026-11-03

Verified 2026-11-03

CosmosClient is the main entry point for the Cosmos TypeScript SDK. It wires together authentication, the registry (Configurator), agent execution (ADK), tool management, file storage, cost limits, observability, and permissions into a single cohesive object.

Configuration

typescript
import { CosmosClient } from '@cosmos/sdk';
import type { CosmosClientConfig } from '@cosmos/sdk';

const config: CosmosClientConfig = {
  orgId: 'your-org-uuid',

  // Optional: canonical Cosmos project UUID, sent as X-Project-Id on REST and WebSocket calls
  projectId: 'your-project-uuid',

  // Per-service URLs (local development ports shown; use your deployment's service hosts elsewhere)
  services: {
    user: 'http://localhost:8101',
    configurator: 'http://localhost:8100',
    tools: 'http://localhost:8102',
    mcp: 'http://localhost:8102',
    adk: 'http://localhost:8103',
    observer: 'http://localhost:8104',
    storage: 'http://localhost:8107',
    chat: 'http://localhost:8108',
    ragflow: 'http://localhost:8200',
  },

  // Optional fallback for services not listed above, only when your deployment
  // routes every service behind one host as <gatewayUrl>/<service>
  // gatewayUrl: 'https://<cosmos-gateway-host>',

  // Authentication
  authManager: {
    tokens: {
      accessToken: '<jwt>',
      refreshToken: '<refresh-jwt>',
      expiresAt: new Date('2026-12-31'),
    },
    onAuthExpired: () => {
      console.log('Session expired — redirect to login');
    },
  },

  // Optional: user ID for ADK sessions
  userId: 'user-123',
};

const cosmos = new CosmosClient(config);

Every request carries Authorization: Bearer <token> and X-Org-Id; see Required headers.

Service URL Resolution

The SDK resolves service URLs in this order:

  1. services.<name> — per-service URL (highest priority)
  2. gatewayUrl — appended with the service name (for example <gatewayUrl>/configurator, <gatewayUrl>/storage)
  3. cosmosBaseUrl — deprecated alias for gatewayUrl

Service names are user, chat, configurator, tools, observer, storage, adk, mcp, and ragflow. A service with no resolvable URL throws when it is first used.

Use resolveServiceUrl(config, 'adk') or resolveAllServiceUrls(config) to inspect resolved URLs programmatically. buildServiceEndpointsFromEnv() builds a services map from whichever of these environment variables are set: COSMOS_USER_SERVICE_URL, COSMOS_CHAT_SERVICE_URL, COSMOS_CONFIGURATOR_SERVICE_URL, COSMOS_TOOLS_SERVICE_URL, COSMOS_OBSERVER_SERVICE_URL, COSMOS_STORAGE_SERVICE_URL, COSMOS_ADK_SERVICE_URL, COSMOS_MCP_SERVICE_URL, and COSMOS_RAGFLOW_SERVICE_URL. See Base URLs for how services are exposed.

Sub-Managers

CosmosClient exposes the following managers as public properties:

PropertyTypePurpose
authAuthManagerToken management, refresh, decode
authzClientAuthzClientUser Service authorization decision helpers
projectClientProjectClientCosmos project listing, lookup, and authorized targets
registryManagerRegistryManagerCRUD and bulk lookups for agents, tools, skills, templates, collections
toolManagerToolManagerLocal tool registration, MCP connections, tool execution
adkClientADKClientAgent converse, sessions, async requests, LLM calls
storageClientStorageClientFile/folder CRUD via Cosmos Storage (DMS)
uploadSessionClientUploadSessionClientAsync direct-to-cloud upload sessions
costLimitsCostLimitsClientPeriod usage, effective cost limits, cost-control config, limit-increase requests
ragflowClientRagflowClient | nullRAGflow search and document parsing (null if service URL not configured)
fileManagerFileManager | nullVirtual file system (null if no adapter configured)
observabilityManagerObservabilityManagerEvent batching and export
eventsSDKEventEmitterInternal event bus for SDK lifecycle events
llmManagerLLMManagerClient-side provider routing and model catalog helpers

Authentication

Setting Tokens

typescript
// At construction time
new CosmosClient({ authManager: { tokens: { ... } } });

// Or later
cosmos.auth.setTokens({
  accessToken: '<jwt>',
  refreshToken: '<refresh>',
  expiresAt: new Date(Date.now() + 3600_000),
});

Token Refresh

The SDK auto-refreshes tokens 60 seconds before expiry. All HTTP clients share the same refresh logic — concurrent requests coalesce into a single refresh call.

typescript
// Manual refresh
const newAccessToken = await cosmos.auth.refresh();

// Check auth status
if (!cosmos.auth.isAuthenticated()) {
  // Token expired and no refresh token available
}

Decoding Tokens

typescript
import { decodeCosmosAccessToken } from '@cosmos/sdk';

const payload = decodeCosmosAccessToken(accessToken);
console.log(payload.email, payload.org_permissions);

OAuth2 Token Refresh

For OAuth2 flows (e.g., third-party integrations):

typescript
const tokenSet = await cosmos.auth.refreshOAuthToken(refreshToken, {
  clientId: 'your-client-id',
  clientSecret: '<client-secret>',
});

See Authentication for the token model shared by all Cosmos APIs.

Service-to-Service Authentication

For backend services, background workers, and automated pipelines that don't have a user session, the SDK supports OAuth2 client_credentials authentication.

Standalone Token Acquisition

Use acquireServiceToken() for one-off calls where you manage the token lifecycle yourself:

typescript
import { acquireServiceToken } from '@cosmos/sdk';

const tokenSet = await acquireServiceToken({
  userServiceUrl: 'https://<user-service-host>',
  clientId: 'your-client-id',
  clientSecret: '<client-secret>',
  scope: 'read write',       // optional, defaults to 'read'
  audience: 'cosmos-storage', // optional — only sent when provided
});

console.log(tokenSet.accessToken);   // JWT string
console.log(tokenSet.expiresAt);     // Unix epoch seconds
// tokenSet.refreshToken is always '' for client_credentials grants

The audience parameter is optional. When omitted, no audience field is sent in the token request. Only include it when the target service requires audience-scoped tokens.

Factory Method for Long-Lived Clients

Use CosmosClient.fromServiceCredentials() when the client should auto-refresh its own tokens. The User Service URL is resolved from services.user or gatewayUrl, like any other service:

typescript
import { CosmosClient } from '@cosmos/sdk';

const cosmos = await CosmosClient.fromServiceCredentials(
  'your-client-id',
  '<client-secret>',
  {
    orgId: 'your-org-uuid',
    projectId: 'your-project-uuid', // optional
    services: {
      user: 'https://<user-service-host>',
      configurator: 'https://<configurator-host>',
      adk: 'https://<adk-host>',
    },
    scope: 'read write',
    audience: 'cosmos-adk',
  },
);

// Use exactly like a user-authenticated client
const agents = await cosmos.searchAgents({ query: 'support' });
await cosmos.shutdown();

The factory acquires the first token before it resolves, so a credential failure surfaces immediately. The same flow is available by passing serviceCredentials: { clientId, clientSecret, scope?, audience? } in CosmosClientConfig.

When to Use Each

ApproachBest for
acquireServiceToken()One-off scripts, Lambda/Cloud Functions, or when you manage tokens externally
CosmosClient.fromServiceCredentials()Long-lived services, background workers, cron jobs that make many SDK calls

Registry Convenience Methods

CosmosClient provides shortcut methods that delegate to registryManager:

Agents

typescript
const agents = await cosmos.searchAgents({ query: 'support', page: 1, pageSize: 10 });
const agent = await cosmos.getAgent('agent-uuid');

Bulk Lookups

Bulk methods resolve many registry references in one round trip instead of one call per ID. Results are cached by the registry cache like other registry reads.

typescript
// Which of these agent IDs exist? (GET /api/v1/agents/bulk-fetch/?agent=<id>&...)
const existingAgents = await cosmos.bulkCheckAgents(['agent-uuid-1', 'agent-uuid-2']);

// Resolve display names across entity types (POST /api/v1/org/bulk-fetch-entities/)
const names = await cosmos.bulkFetchEntityNames([
  { type: 'agent', id: 'agent-uuid-1' },
  { type: 'collection', id: 'collection-uuid' },
  { type: 'skill', id: 'skill-uuid' },
]);
// [{ type: 'agent', id: 'agent-uuid-1', name: 'My Agent' }, ...]

// Which IDs of one type exist?
const existing = await cosmos.bulkCheckEntities('collection', collectionIds);
const missing = collectionIds.filter((id) => !existing.has(id));
  • bulkFetchEntityNames returns found entities in request order. Unknown, cross-org, and deleted IDs are omitted rather than raising an error. The server accepts at most 200 items per call.
  • Supported entity types are listed in RegistryManager.BULK_ENTITY_TYPES: agent, app, tool, skill, template, business_event, analyzer, collection, graph.
  • bulkCheckEntities(type, ids) is a wrapper over bulkFetchEntityNames that returns a Set of the IDs that exist.

Data Sources

typescript
const dataSources = await cosmos.searchDataSources({ query: 'warehouse', engine: 'sqlite' });

const source = await cosmos.createDataSource({
  name: 'Assessment SQLite',
  engine: 'sqlite',
  connection_profile: { path: '/dms/projects/acme/assessment.db' },
});

await cosmos.syncDataSourceTool(source.id);
const test = await cosmos.testDataSource(source.id, 'SELECT 1');
console.log(dataSources.total, test);

Authorization Decisions

typescript
const allowed = await cosmos.authzClient.can({
  actor: { type: 'user', id: 'user-uuid' },
  action: 'bridge.connect',
  resource: { type: 'organization', id: config.orgId },
  context: { channel: 'jumpstart' },
});

Skills

typescript
const skills = await cosmos.searchSkills({ tags: ['customer-service'] });
const detail = await cosmos.getSkillDetail('skill-uuid');
const created = await cosmos.createSkill({
  name: 'greeting-skill',
  description: 'Greets the user',
  configuration: { instructions: 'Always greet warmly.' },
});
await cosmos.deploySkill(created.id);

Tools

typescript
const tools = await cosmos.searchTools({ type: 'api', query: 'weather' });
const detail = await cosmos.getToolDetail('tool-uuid', 'api');

Templates

typescript
const templates = await cosmos.searchTemplates();
const detail = await cosmos.getTemplateDetail('template-uuid');

Collections

typescript
const collections = await cosmos.searchCollections();
const col = await cosmos.createCollection({ name: 'Q1 Reports', description: '...' });
await cosmos.reindexCollection(col.id);

LLM Models

typescript
const models = await cosmos.fetchAvailableModels();
const orgModels = await cosmos.fetchOrgModels();
const byotSchema = await cosmos.fetchByotSchema();

LLM manager calls discover model/BYOT metadata through Configurator and route completions through locally registered providers.

User & Roles

typescript
const roles = await cosmos.fetchOrgRoles({ expand: 'permissions' });
const role = await cosmos.fetchRoleDetail(roleId);
const userRoles = await cosmos.fetchOrgUserRoles();

Cost Limits

cosmos.costLimits covers period usage, cost-control configuration, and the limit-increase request workflow.

typescript
// Effective limits for the signed-in user (no admin permission required)
const limits = await cosmos.costLimits.getMyCostLimits();
// { session: { enabled, limit_usd, is_custom }, weekly: {...}, monthly: {...} }

// Weekly and monthly usage for the signed-in user (Observer)
const usage = await cosmos.costLimits.getCurrentPeriodUsage();

// Org-wide cost-control configuration (admin)
const config = await cosmos.costLimits.getCostControlConfig();
MethodEndpointNotes
getMyCostLimits()GET /api/v1/cost-control-config/mine/ (Configurator)Returns MyCostLimits: session, weekly, and monthly entries, each { enabled: boolean, limit_usd: string | null, is_custom: boolean }. Each entry is the effective limit (org configuration merged with any per-user override); is_custom marks a per-user override.
getCurrentPeriodUsage()GET /api/v1/costing/users/me/period-usage/current (Observer)Throws if no Observer URL is configured.
getCostControlConfig()GET /api/v1/cost-control-config/ (Configurator)Org configuration for administrators.
createLimitIncreaseRequest(input)POST /api/v1/limit-increase-requests/The server snapshots the requester's current limits; the input carries only the requested values.
getMyLimitIncreaseRequests(), getMyPendingLimitIncreaseRequest()ConfiguratorThe current user's request history and pending request.
listLimitIncreaseRequests(), getLimitIncreaseRequest(id), approveLimitIncreaseRequest(), rejectLimitIncreaseRequest()ConfiguratorReviewer workflow.

Tool Registration

Register local tools that the ADK v2 WebSocket can call back into:

typescript
cosmos.registerTool(
  'get_weather',
  ['weather.current'],
  {
    name: 'get_weather',
    description: 'Get current weather for a city',
    inputSchema: {
      type: 'object',
      properties: { city: { type: 'string' } },
      required: ['city'],
    },
  },
  async (input) => {
    const city = input.city as string;
    return { ok: true, data: { temp: 22, unit: 'C', city } };
  },
);

When a handler returns { ok: false, error: { code, message } }, the SDK sends the error message as the tool result's error text, so the model sees the actual failure reason. See Tool Results and Errors.

MCP Server Connections

Connect to external MCP-compatible tool servers:

typescript
await cosmos.connectMCP({
  id: 'cosmos',
  transport: 'network',
  url: 'http://localhost:8102/mcp/',
  headers: { Authorization: `Bearer ${token}`, 'X-Org-Id': orgId },
});

ADK v2 WebSocket (Streaming)

sendMessageViaADK manages a persistent WebSocket to ADK v2, enabling streaming responses and local tool execution:

typescript
const result = await cosmos.sendMessageViaADK(null, 'Hello!', {
  agentId: 'agent-uuid',
  agentVersion: '1.0',
  onChunk: (text) => process.stdout.write(text),
});

// Follow-up on same session
const result2 = await cosmos.sendMessageViaADK(
  result.sessionId,
  'Tell me more',
  { onChunk: (text) => process.stdout.write(text) },
);

// Access current session ID
console.log(cosmos.adkSessionId);

// Clean up WebSocket
cosmos.closeADKSession();

ADK owns context compaction for the session; the SDK does not send compaction controls. Pass executionContext (including manifestHash) when the caller pins an execution manifest. See ADKClient Reference for all send options.

File System

If a FileSystemAdapter is provided, CosmosClient creates a FileManager:

typescript
import { LocalFileSystemAdapter } from '@cosmos/sdk';

const cosmos = new CosmosClient({
  // ...
  fileSystem: {
    adapter: new LocalFileSystemAdapter('/data/workspace'),
  },
});

const files = await cosmos.fileManager!.list('/');
const content = await cosmos.fileManager!.read('/report.md');

Built-in adapters: LocalFileSystemAdapter, CosmosDMSAdapter, MCPFileSystemAdapter.

createDocumentTools() builds document read/write tools over a DocumentStore. The write tools reject projected or partial payloads instead of silently writing incomplete content.

Observability

typescript
import type { ObservabilityAdapter } from '@cosmos/sdk';

const myAdapter: ObservabilityAdapter = {
  adapterId: 'my-backend',
  send: async (events) => { /* push to your analytics backend */ },
};

const cosmos = new CosmosClient({
  // ...
  observability: {
    adapter: myAdapter,
    batchSize: 50,
    flushIntervalMs: 5000,
    enabled: true,
  },
});

// Check stats
const stats = cosmos.observabilityManager.getStats();
console.log(`Events sent: ${stats.eventsSent}`);

Lifecycle

typescript
// Shut down cleanly — closes WebSocket, flushes events, removes listeners
await cosmos.shutdown();

Exports Cheat Sheet

All public exports are available from the package root:

typescript
import {
  // Main client
  CosmosClient,

  // Auth
  AuthManager, AuthzClient, decodeCosmosAccessToken, refreshCosmosToken, acquireServiceToken,

  // Projects
  ProjectClient,

  // ADK
  ADKClient, ADKV2StreamSession, toADKV2ToolDefs,

  // Registry
  RegistryManager, flattenAgentConfig, buildResourceInventory,

  // Tools
  ToolManager,

  // File
  FileManager, LocalFileSystemAdapter, CosmosDMSAdapter, MCPFileSystemAdapter,
  createDocumentTools,

  // Storage
  StorageClient, UploadSessionClient, uploadFileAsync, uploadFileToCloud,

  // Cost limits
  CostLimitsClient,

  // RAGflow
  RagflowClient,

  // LLM
  LLMManager,

  // Permissions
  PermissionManager,

  // Observability
  ObservabilityManager, NoopAdapter,

  // Events
  SDKEventEmitter,

  // Context
  createContextActivationTools, buildInventoryPrompt, buildRuntimeContextCard,

  // HTTP
  CosmosHttpClient, CosmosApiError, CosmosAuthError,

  // Utilities
  postForm, resolveServiceUrl, resolveAllServiceUrls,
  buildServiceEndpointsFromEnv, resolveStorageDownloadUrl,
  setLogLevel, generateId,
} from '@cosmos/sdk';

Cost-limit types (MyCostLimit, MyCostLimits, CostControlConfig, PeriodUsageResponse, LimitIncreaseRequest, and related inputs) and RAGflow parse types (RagflowParseFileInput, RagflowParseOptions, RagflowParseResponse) are exported as types.

See Also