Infactory TypeScript SDK

Infactory TypeScript SDK

Infactory TypeScript SDK for use with the Infactory Workshop, MCP Server and API

infactory-io

开发者工具
访问服务器

README

Infactory TypeScript SDK

Official TypeScript SDK for interacting with the Infactory AI platform. This SDK allows you to programmatically access and manage your data, projects, and queries through the Infactory API.

Installation

npm install @infactory/infactory-ts

Configuration

Before using the SDK, you need to set up your Infactory API credentials:

  1. Obtain an API key from the Infactory Workshop
  2. Use the API key to initialize the client

Quick Start

import { InfactoryClient } from '@infactory/infactory-ts';

// Initialize the client with your API key
const client = new InfactoryClient({
  apiKey: 'your-api-key-here',
  // Optional: baseURL: 'https://api.infactory.ai' // Use custom API endpoint if needed
});

// Example: Get current user information
async function getCurrentUser() {
  const response = await client.users.getCurrentUser();
  if (response.error) {
    console.error(`Error: ${response.error.message}`);
    return null;
  }
  return response.data;
}

// Example: List all projects
async function listProjects() {
  const response = await client.projects.getProjects();
  if (response.error) {
    console.error(`Error: ${response.error.message}`);
    return [];
  }
  return response.data;
}

Environment Variables

The SDK supports loading configuration from environment variables:

# Required
NF_API_KEY=your-api-key-here

# Optional - defaults to https://api.infactory.ai
NF_BASE_URL=https://api.infactory.ai

You can load these variables from a .env file using dotenv:

import * as dotenv from 'dotenv';
import { InfactoryClient } from '@infactory/infactory-ts';

// Load environment variables
dotenv.config();

// Create client using environment variables
const client = new InfactoryClient({
  apiKey: process.env.NF_API_KEY || '',
});

Available APIs

The SDK provides access to the following Infactory API resources:

  • Projects - Create and manage projects
  • Teams - Manage teams and team memberships
  • Organizations - Access organization information
  • Users - User management and authentication
  • Auth - API key management
  • Chat - Interact with the chat interface
  • Datasources - Connect to and manage data sources
  • Datalines - Access and transform data
  • QueryPrograms - Create, run, and publish queries
  • APIs - Deploy and manage API endpoints
  • Credentials - Manage connection credentials
  • Secrets - Store and manage secrets
  • Tasks - Track and manage tasks
  • Events - Access event information

Common Workflows

Creating a Project and Uploading Data

// Create a new project
const projectResponse = await client.projects.createProject({
  name: 'Stock Analysis Project',
  team_id: teamId,
  description: 'Project for analyzing stock data',
});
const project = projectResponse.data;

// Create a datasource
const datasourceResponse = await client.datasources.createDatasource({
  name: 'Stock Data',
  project_id: project.id,
  type: 'csv',
});
const datasource = datasourceResponse.data;

// Upload a CSV file (This is a simplified example)
const formData = new FormData();
formData.append('file', fs.createReadStream('./data/stocks.csv'));

// Upload using the datasource
await fetch(
  `${client.getBaseURL()}/v1/actions/load/${project.id}?datasource_id=${datasource.id}`,
  {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${client.getApiKey()}`,
    },
    body: formData,
  },
);

Working with Query Programs

// Get query programs for a project
const queryProgramsResponse =
  await client.queryprograms.getQueryProgramsByProject(projectId);
const queryPrograms = queryProgramsResponse.data;

// Execute a query program
const evaluateResponse =
  await client.queryprograms.executeQueryProgram(queryProgramId);
const queryResult = evaluateResponse.data;

// Publish a query program to make it available as an API
await client.queryprograms.publishQueryProgram(queryProgramId);

Accessing APIs

// Get APIs for a project
const apisResponse = await client.apis.getProjectApis(projectId);
const apis = apisResponse.data;

// Get endpoints for an API
const endpointsResponse = await client.apis.getApiEndpoints(apiId);
const endpoints = endpointsResponse.data;

Error Handling

The SDK provides a consistent error handling strategy with specific error classes for different types of errors:

import {
  InfactoryClient,
  AuthenticationError,
  PermissionError,
  NotFoundError,
} from '@infactory/infactory-ts';

async function handleErrors() {
  try {
    const client = new InfactoryClient({ apiKey: 'your-api-key' });
    const response = await client.projects.getProject('non-existent-id');
    return response.data;
  } catch (error) {
    if (error instanceof AuthenticationError) {
      console.error('Authentication failed. Please check your API key.');
    } else if (error instanceof PermissionError) {
      console.error('You do not have permission to access this resource.');
    } else if (error instanceof NotFoundError) {
      console.error('The requested resource was not found.');
    } else {
      console.error(`Unexpected error: ${error.message}`);
    }
  }
}

Handling Streaming Responses

Some API endpoints like executeQueryProgram can return streaming responses. The SDK provides utilities to handle these responses:

import {
  InfactoryClient,
  isReadableStream,
  processStreamToApiResponse,
} from '@infactory/infactory-ts';

async function handleStreamingResponse() {
  const client = new InfactoryClient({ apiKey: 'your-api-key' });

  // This may return a stream or a regular response
  const result = await client.queryprograms.executeQueryProgram(
    queryProgramId,
    { stream: true },
  );

  if (isReadableStream(result)) {
    // Process the stream into a regular API response
    const apiResponse = await processStreamToApiResponse(result);
    return apiResponse.data;
  } else {
    // Handle regular API response
    return result.data;
  }
}

Complete Examples

For complete examples, see:

  • example.ts - Basic SDK usage examples
  • infactory-e2e-test.ts - End-to-end testing workflow including project creation, data upload, query execution, and API usage

Command Line Tools

To run the included example files:

# Set up your API key
export NF_API_KEY=your-api-key-here

# Run the basic example
npm run example

# Run the end-to-end test
npm run e2e-test

Development

Building from Source

git clone https://github.com/infactory-io/infactory-ts.git
cd infactory-ts
npm install
npm run e2e-test

Testing the SDK

The SDK includes a comprehensive test suite using Jest with several types of tests:

Unit Tests

Unit tests verify individual components of the SDK in isolation:

npm run test:unit

Integration Tests

Integration tests verify how components work together and with the Infactory API:

npm run test:integration

Mock Service Worker Tests

MSW tests simulate API interactions using request interception:

npm run test:msw

Running All Tests

To run the entire test suite:

npm test

Test Coverage

Generate test coverage reports:

npm run test:coverage

Setting Up Tests

For contributors writing tests:

  1. Unit Tests: Place in src/__tests__/ and name as *.test.ts
  2. Integration Tests: Place in src/__tests__/integration/ directory
  3. MSW Tests: Place in src/__tests__/msw/ directory

Testing Dependencies

The test suite uses several tools:

  • Jest: Test runner and assertion library
  • ts-jest: TypeScript support for Jest
  • jest-fetch-mock: Mocking fetch requests
  • nock: HTTP server mocking
  • MSW: API mocking via request interception

License

This Infactory TypeScript SDK is licensed under the MIT License. See the LICENSE file for more details.

推荐服务器

Playwright MCP Server

Playwright MCP Server

一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。

官方
精选
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。

官方
精选
本地
TypeScript
MCP Package Docs Server

MCP Package Docs Server

促进大型语言模型高效访问和获取 Go、Python 和 NPM 包的结构化文档,通过多语言支持和性能优化来增强软件开发。

精选
本地
TypeScript
Claude Code MCP

Claude Code MCP

一个实现了 Claude Code 作为模型上下文协议(Model Context Protocol, MCP)服务器的方案,它可以通过标准化的 MCP 接口来使用 Claude 的软件工程能力(代码生成、编辑、审查和文件操作)。

精选
本地
JavaScript
@kazuph/mcp-taskmanager

@kazuph/mcp-taskmanager

用于任务管理的模型上下文协议服务器。它允许 Claude Desktop(或任何 MCP 客户端)在基于队列的系统中管理和执行任务。

精选
本地
JavaScript
mermaid-mcp-server

mermaid-mcp-server

一个模型上下文协议 (MCP) 服务器,用于将 Mermaid 图表转换为 PNG 图像。

精选
JavaScript
Jira-Context-MCP

Jira-Context-MCP

MCP 服务器向 AI 编码助手(如 Cursor)提供 Jira 工单信息。

精选
TypeScript
Linear MCP Server

Linear MCP Server

一个模型上下文协议(Model Context Protocol)服务器,它与 Linear 的问题跟踪系统集成,允许大型语言模型(LLM)通过自然语言交互来创建、更新、搜索和评论 Linear 问题。

精选
JavaScript
Sequential Thinking MCP Server

Sequential Thinking MCP Server

这个服务器通过将复杂问题分解为顺序步骤来促进结构化的问题解决,支持修订,并通过完整的 MCP 集成来实现多条解决方案路径。

精选
Python
Curri MCP Server

Curri MCP Server

通过管理文本笔记、提供笔记创建工具以及使用结构化提示生成摘要,从而实现与 Curri API 的交互。

官方
本地
JavaScript