Skip to content

documenso/sdk-typescript

Repository files navigation

Documenso Logo

 

Documenso TypeScript SDK

A type-safe SDK for seamless integration with Documenso v2 API, providing first-class TypeScript support.

This SDK offers a strongly-typed interface to interact with Documenso's API, enabling you to:

  • Handle document signing workflows with full type safety
  • Leverage autocomplete in your IDE
  • Catch potential errors at compile time

The full Documenso API can be viewed here, which includes TypeScript examples.

⚠️ Warning

Documenso v2 API and SDKs are currently in beta. There may be to breaking changes.

To keep updated, please follow the discussions here:

Table of Contents

SDK Installation

The SDK can be installed with either npm, pnpm, bun or yarn package managers.

NPM

npm add @documenso/sdk-typescript

PNPM

pnpm add @documenso/sdk-typescript

Bun

bun add @documenso/sdk-typescript

Yarn

yarn add @documenso/sdk-typescript zod

# Note that Yarn does not install peer dependencies automatically. You will need
# to install zod as shown above.

Model Context Protocol (MCP) Server

This SDK is also an installable MCP server where the various SDK methods are exposed as tools that can be invoked by AI applications.

Node.js v20 or greater is required to run the MCP server from npm.

Claude installation steps

Add the following server definition to your claude_desktop_config.json file:

{
  "mcpServers": {
    "Documenso": {
      "command": "npx",
      "args": [
        "-y", "--package", "@documenso/sdk-typescript",
        "--",
        "mcp", "start",
        "--api-key", "..."
      ]
    }
  }
}
Cursor installation steps

Create a .cursor/mcp.json file in your project root with the following content:

{
  "mcpServers": {
    "Documenso": {
      "command": "npx",
      "args": [
        "-y", "--package", "@documenso/sdk-typescript",
        "--",
        "mcp", "start",
        "--api-key", "..."
      ]
    }
  }
}

You can also run MCP servers as a standalone binary with no additional dependencies. You must pull these binaries from available Github releases:

curl -L -o mcp-server \
    https://github.com/{org}/{repo}/releases/download/{tag}/mcp-server-bun-darwin-arm64 && \
chmod +x mcp-server

If the repo is a private repo you must add your Github PAT to download a release -H "Authorization: Bearer {GITHUB_PAT}".

{
  "mcpServers": {
    "Todos": {
      "command": "./DOWNLOAD/PATH/mcp-server",
      "args": [
        "start"
      ]
    }
  }
}

For a full list of server arguments, run:

npx -y --package @documenso/sdk-typescript -- mcp start --help

Requirements

For supported JavaScript runtimes, please consult RUNTIMES.md.

Authentication

To use the SDK, you will need a Documenso API key which can be created here.

const documenso = new Documenso({
  apiKey: process.env["DOCUMENSO_API_KEY"] ?? "",
});

Document creation example

Currently creating a document involves two steps:

  1. Create the document
  2. Upload the PDF

This is a temporary measure, in the near future prior to the full release we will merge these two tasks into one request.

Here is a full example of the document creation process which you can copy and run.

Note that the function is temporarily called createV0, which will be replaced by create once we resolve the 2 step workaround.

import { Documenso } from "@documenso/sdk-typescript";
import fs from "fs";

const documenso = new Documenso({
  apiKey: process.env["DOCUMENSO_API_KEY"] ?? "",
});

async function uploadFileToPresignedUrl(filePath: string, uploadUrl: string) {
  const fileBuffer = await fs.promises.readFile(filePath);

  // Make PUT request to pre-signed URL
  const response = await fetch(uploadUrl, {
    method: "PUT",
    body: fileBuffer,
    headers: {
      "Content-Type": "application/octet-stream",
    },
  });

  if (!response.ok) {
    throw new Error(`Upload failed with status: ${response.status}`);
  }
}

const main = async () => {
  const createDocumentResponse = await documenso.documents.createV0({
    title: "Document title",
    recipients: [
      {
        email: "[email protected]",
        name: "Example Doe",
        role: "SIGNER",
        fields: [
          {
            type: "SIGNATURE",
            pageNumber: 1,
            pageX: 10,
            pageY: 10,
            width: 10,
            height: 10,
          },
          {
            type: "INITIALS",
            pageNumber: 1,
            pageX: 20,
            pageY: 20,
            width: 10,
            height: 10,
          },
        ],
      },
      {
        email: "[email protected]",
        name: "Admin Doe",
        role: "APPROVER",
        fields: [
          {
            type: "SIGNATURE",
            pageNumber: 1,
            pageX: 10,
            pageY: 50,
            width: 10,
            height: 10,
          },
        ],
      },
    ],
    meta: {
      timezone: "Australia/Melbourne",
      dateFormat: "MM/dd/yyyy hh:mm a",
      language: "de",
      subject: "Email subject",
      message: "Email message",
      emailSettings: {
        recipientRemoved: false,
      },
    },
  });

  const { document, uploadUrl } = createDocumentResponse;

  // Upload the PDF you want attached to the document.
  // Replace demo.pdf with your file to upload relative to this file.
  await uploadFileToPresignedUrl("./demo.pdf", uploadUrl);

  return document;
};

main()

Available Resources and Operations

Available methods
  • get - Get document recipient
  • create - Create document recipient
  • createMany - Create document recipients
  • update - Update document recipient
  • updateMany - Update document recipients
  • delete - Delete document recipient
  • get - Get template recipient
  • create - Create template recipient
  • createMany - Create template recipients
  • update - Update template recipient
  • updateMany - Update template recipients
  • delete - Delete template recipient

Retries

Some of the endpoints in this SDK support retries. If you use the SDK without any configuration, it will fall back to the default retry strategy provided by the API. However, the default retry strategy can be overridden on a per-operation basis, or across the entire SDK.

To change the default retry strategy for a single API call, simply provide a retryConfig object to the call:

import { Documenso } from "@documenso/sdk-typescript";

const documenso = new Documenso({
  apiKey: process.env["DOCUMENSO_API_KEY"] ?? "",
});

async function run() {
  const result = await documenso.documents.find({}, {
    retries: {
      strategy: "backoff",
      backoff: {
        initialInterval: 1,
        maxInterval: 50,
        exponent: 1.1,
        maxElapsedTime: 100,
      },
      retryConnectionErrors: false,
    },
  });

  console.log(result);
}

run();

If you'd like to override the default retry strategy for all operations that support retries, you can provide a retryConfig at SDK initialization:

import { Documenso } from "@documenso/sdk-typescript";

const documenso = new Documenso({
  retryConfig: {
    strategy: "backoff",
    backoff: {
      initialInterval: 1,
      maxInterval: 50,
      exponent: 1.1,
      maxElapsedTime: 100,
    },
    retryConnectionErrors: false,
  },
  apiKey: process.env["DOCUMENSO_API_KEY"] ?? "",
});

async function run() {
  const result = await documenso.documents.find({});

  console.log(result);
}

run();

Error Handling

DocumensoError is the base class for all HTTP error responses. It has the following properties:

Property Type Description
error.message string Error message
error.statusCode number HTTP response status code eg 404
error.headers Headers HTTP response headers
error.body string HTTP body. Can be empty string if no body is returned.
error.rawResponse Response Raw HTTP response
error.data$ Optional. Some errors may contain structured data. See Error Classes.

Example

import { Documenso } from "@documenso/sdk-typescript";
import * as errors from "@documenso/sdk-typescript/models/errors";

const documenso = new Documenso({
  apiKey: process.env["DOCUMENSO_API_KEY"] ?? "",
});

async function run() {
  try {
    const result = await documenso.documents.find({});

    console.log(result);
  } catch (error) {
    // The base class for HTTP error responses
    if (error instanceof errors.DocumensoError) {
      console.log(error.message);
      console.log(error.statusCode);
      console.log(error.body);
      console.log(error.headers);

      // Depending on the method different errors may be thrown
      if (error instanceof errors.DocumentFindDocumentsBadRequestError) {
        console.log(error.data$.message); // string
        console.log(error.data$.code); // string
        console.log(error.data$.issues); // DocumentFindDocumentsBadRequestIssue[]
      }
    }
  }
}

run();

Error Classes

Primary error:

Less common errors (104)

Network errors:

Inherit from DocumensoError:

* Check the method documentation to see if the error is applicable.

Server Selection

Override Server URL Per-Client

The default server can be overridden globally by passing a URL to the serverURL: string optional parameter when initializing the SDK client instance. For example:

import { Documenso } from "@documenso/sdk-typescript";

const documenso = new Documenso({
  serverURL: "https://app.documenso.com/api/v2-beta",
  apiKey: process.env["DOCUMENSO_API_KEY"] ?? "",
});

async function run() {
  const result = await documenso.documents.find({});

  console.log(result);
}

run();

Debugging

You can setup your SDK to emit debug logs for SDK requests and responses.

You can pass a logger that matches console's interface as an SDK option.

Warning

Beware that debug logging will reveal secrets, like API tokens in headers, in log messages printed to a console or files. It's recommended to use this feature only during local development and not in production.

import { Documenso } from "@documenso/sdk-typescript";

const sdk = new Documenso({ debugLogger: console });

You can also enable a default debug logger by setting an environment variable DOCUMENSO_DEBUG to true.

Development

Maturity

This SDK is in beta, and there may be breaking changes between versions without a major version update. Therefore, we recommend pinning usage to a specific package version. This way, you can install the same version each time without breaking changes unless you are intentionally looking for the latest version.

Contributions

While we value open-source contributions to this SDK, this library is generated programmatically. Any manual changes added to internal files will be overwritten on the next generation. We look forward to hearing your feedback. Feel free to open a PR or an issue with a proof of concept and we'll do our best to include it in a future release.

SDK Created by Speakeasy

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors 5