Unqork documentation is available in two workspaces: UnqorkAI for the latest AI-first platform, and legacy Unqork for previous versions. Use the drop-down near the logo to switch.

Build an Agent That Connects to the MCP Server

Prev Next

The MCP server is a Beta feature for environments with UnqorkAI. Test each published tool and verify its results before relying on it.

An agent is a program that gives an AI model a list of tools and runs the tools that the model picks. This article describes how to write an agent in Node.js that connects to your environment's MCP server and calls the tools you published there.

The agent is your organization's program, not part of Unqork. Your organization writes, hosts, and runs it in its own infrastructure, and it reaches your environment only through the MCP server's endpoint. Unqork provides the tools and checks each call. Unqork does not host, run, or monitor the agent. The program can use any model that supports tool calls, like Claude. The snippets are short examples, so add your own hosting, sign-in, and testing before you rely on them.

Building an agent is an advanced task for an engineer or an AI model. This article describes custom software development in Node.js outside Unqork.

Requirements

Before you begin, confirm the following:

  • A published tool: An API module is published as a tool, and an Express role holds Write on it. See Publish API Modules as MCP Tools.
  • An API credential: The credential holds only that role, and you stored its Client Secret in a secrets manager. See Create the Agent's API Credential.
  • A place to run the agent: A server, container, or cloud account that you manage. The agent does not run in Unqork.
  • Node.js: Version 22 or later, so the runtime still receives security fixes. The MCP client SDK requires 18 or later.

What the Agent Does

The agent runs on your side of the connection. For each message, the agent repeats the following loop:

  1. Get a token, or reuse one that is still valid.
  2. List the tools that the credential can call.
  3. Give the tools and the message to the model.
  4. Run each tool call that the model requests.
  5. Return the results to the model, and repeat from step 3 until the model answers.

The MCP server fixes the identity, the token, and the connection. You build and run everything else.

Part Fixed by the MCP Server Your Choice
Identity An Express role with Default Permission No Access, held by an Express API credential. One role for each agent, or for each group of agents with the same reach.
Token The client credentials grant, with resource set to the MCP endpoint, renewed every 60 minutes. How your code loads the Client Secret from your secrets manager.
Connection Streamable HTTP with an Authorization: Bearer header. The MCP client SDK.
Hosting Not part of the MCP server. The agent runs outside Unqork. Where the agent runs, like your own servers or cloud account, and how you deploy, monitor, and update it.
Model Not part of the MCP server. Any model that supports tool calls.
Purpose Not part of the MCP server. The system prompt that defines the agent's job.
Interface Not part of the MCP server. A chat page, a queue, a scheduled job, and so on.

Start with a module that a person could ask for in one sentence. A good first tool has the following qualities:

  • It is an API module that runs server-side only.
  • It does one job, like looking up a record or quoting a price.
  • It reads data instead of changing it, so a wrong call costs nothing.
  • It takes inputs that a caller knows, like a customer name or an order ID, instead of internal record IDs.
  • It returns a few outputs that matter.

Publish the module as described in Publish an API Module as a Tool. The model reads only the tool's name and description when it chooses a tool, so state what the tool does and when to use it.

Get and Renew Tokens

A token lasts 60 minutes and cannot be refreshed. The following token provider replaces tokens.getToken() in the connect example. It reuses a valid token, requests a new one a minute before expiry, and lets callers that arrive together share one request.

Load UNQORK_CLIENT_ID and UNQORK_CLIENT_SECRET into environment variables from your secrets manager when the agent begins. The values tokenUrl and mcpUrl are the addresses from Get a Token.

export class AgentError extends Error {}

export function createTokenProvider({ tokenUrl, mcpUrl, clientId, clientSecret }) {
  let cached = null // { token, expiresAt }
  let pending = null // one request that every waiting caller shares

  async function requestToken() {
    const basic = Buffer.from(`${clientId}:${clientSecret}`).toString('base64')
    const response = await fetch(tokenUrl, {
      method: 'POST',
      headers: { authorization: `Basic ${basic}`, 'content-type': 'application/x-www-form-urlencoded' },
      body: new URLSearchParams({ grant_type: 'client_credentials', resource: mcpUrl }),
      redirect: 'error'
    })
    if (!response.ok) {
      // Report the status only, so neither the secret nor the response body reaches a log
      throw new AgentError(`The token request failed with HTTP ${response.status}.`)
    }
    const { access_token: token, expires_in: expiresIn } = await response.json()
    cached = { token, expiresAt: Date.now() + expiresIn * 1000 }
    return token
  }

  return {
    async getToken() {
      // Renew 60 seconds early so a token never expires in flight
      if (cached && Date.now() < cached.expiresAt - 60_000) return cached.token
      pending ??= requestToken().finally(() => { pending = null })
      return pending
    },
    invalidate() { cached = null }
  }
}

The error carries the status only. To read the server's reason, repeat the request in the Postman test.

List Tools on Every Turn

Wrap fetch so that every request carries the current token and retries once when the server rejects it. The server answers 401 for a token it does not accept and 440 Login Timeout for an expired one. Treat both the same way.

export function withBearer(tokens) {
  return async (url, init = {}) => {
    const send = async () => {
      const headers = new Headers(init.headers)
      headers.set('authorization', `Bearer ${await tokens.getToken()}`)
      return fetch(url, { ...init, headers, redirect: 'error' })
    }
    const response = await send()
    if (response.status !== 401 && response.status !== 440) return response
    tokens.invalidate() // the token expired or was rejected, so get a new one and retry once
    return send()
  }
}

Pass the wrapper as the fetch option when you create the transport, like new StreamableHTTPClientTransport(url, { fetch: withBearer(tokens) }).

The server does not tell a connected client when its tools change. List the tools at the beginning of every turn, so a tool that you publish or switch off takes effect on the agent's next message. Each list counts as one request toward the call limits.

If the agent cannot connect or lists no tools, check the following:

Symptom Cause and Fix
Token request returns 401 The Client ID or Client Secret is wrong.
Token request returns 403 The token endpoint refused the credential. Confirm that it is an Express API credential and that the request goes to the Express host.
Token request returns 400 The resource value does not name the MCP endpoint exactly, the environment does not have UnqorkAI, or the Authorization header is missing or invalid.
Token request returns 429 The credential's account is locked after repeated failed sign-ins. Wait for the lock to clear, or ask an administrator to check the credential.
Repeated 401 The token was requested without resource, so the MCP endpoint does not accept it.
Empty tool list The role does not have Write on the module, or the tool is switched off on MCP Settings.

Call Tools for the Model

Convert each tool to the format that your model expects, and run each call that the model requests. Most model APIs accept the tool's inputSchema unchanged, because it is JSON Schema.

// Run once per turn, so tools you publish or switch off take effect without a restart
export async function loadModelTools(client) {
  const { tools } = await client.listTools()
  return tools.map((tool) => ({
    name: tool.name,
    description: tool.description,
    inputSchema: tool.inputSchema // JSON Schema, which most model APIs accept as is
  }))
}

// Allow at most `max` calls at a time, to stay inside the environment's in-flight limit
export function createLimiter(max) {
  let active = 0
  const waiting = []
  return async (task) => {
    if (active >= max) await new Promise((resolve) => waiting.push(resolve)) // the slot is handed over
    else active += 1
    try {
      return await task()
    } finally {
      const next = waiting.shift()
      if (next) next()
      else active -= 1
    }
  }
}

export async function runToolCall(client, limit, call) {
  try {
    const result = await limit(() => client.callTool({ name: call.name, arguments: call.arguments }))
    // isError means the call failed, and the text states the cause, like the field and the rule
    return { isError: result.isError === true, content: result.structuredContent ?? result.content }
  } catch {
    return { isError: true, content: 'The tool could not be called.' }
  }
}

Create the limiter with createLimiter(2), which matches the default of two calls running at one time for each credential. A third call fails immediately and is not queued, and models often request several tools in one turn.

  • Outputs: The structuredContent value holds the tool's outputs.
  • Failed calls: When isError is true, the call ran and failed. For a validation failure, the message names the field and the rule. For a limit or an execution failure, the message states the cause. Return the message to the model so the model can correct the call or stop.
  • Request limit: The endpoint returns 429 after 120 requests in a minute for a credential. Wait the seconds that the message states before you retry.

Keep the Agent Secure

Because you host the agent, you also secure it. Unqork secures the MCP server, but not the program that calls it or the place where it runs. The credential identifies the agent, and it can run every module that its role reaches. Apply your organization's encryption and key-handling standards to the Client Secret and to every token. The following practices keep the agent from leaking them:

  • Secrets: Load the Client ID and Client Secret from a secrets manager when the agent begins. Never place them in code, in source control, or in a log.
  • Logs: Write one JSON line for each event, with names and statuses only. Never log tool arguments, tool results, tokens, or request headers, because they can hold personal data.
  • Issues: Show people only messages that you wrote. A raw error message or a stack trace can reveal how your agent is built.
  • Outbound requests: Send requests only to your own Unqork environment, over https://, and refuse redirects. Also add network rules that block private and link-local address ranges, including the cloud provider's metadata service.
  • People: The credential does not identify the person who is chatting. Authenticate people before they reach the agent.
const SECRET_KEY = /authorization|cookie|secret|password|api[-_]?key|token/i

// One JSON line per event. Log names and statuses, never tool arguments, results, or headers.
export function log(level, event, fields = {}) {
  const safe = Object.fromEntries(
    Object.entries(fields).map(([key, value]) => [key, SECRET_KEY.test(key) ? '[redacted]' : value])
  )
  console.log(JSON.stringify({ time: new Date().toISOString(), level, event, ...safe }))
}

// Send requests only to your own Unqork environment, over https
export function assertUnqorkUrl(url, expectedHost) {
  const parsed = new URL(url)
  if (parsed.protocol !== 'https:' || parsed.host !== expectedHost) {
    throw new AgentError('The request was blocked because it does not go to your Unqork environment.')
  }
}

// Show a person only the messages you wrote, never a stack trace or an upstream message
export function toPublicMessage(error) {
  return error instanceof AgentError ? error.message : 'Something went wrong. Try again.'
}

Call assertUnqorkUrl(tokenUrl, expectedHost) and assertUnqorkUrl(mcpUrl, expectedHost) once when the agent begins, with the Express host as expectedHost. A wrong setting then stops the agent before it sends a credential anywhere else. The token provider and withBearer do not call it themselves.

Pin every dependency to an exact version, like @modelcontextprotocol/sdk@1.32.2 in the connect example. An update then cannot change the agent without a review.

Go Further

  • Least access: Grant Write on only the modules that the agent needs. See How an Agent Gets Access.
  • Write tools: Add tools that change data only after you test the read tools, and set a tighter limit on them. See Tool Settings.
  • More environments: Move the agent from a test environment to production with the steps in Set Up the Agent in Another Environment.
  • Separate credentials: Give each deployment its own credential, because copies of an agent that share one credential share one request allowance.

Changelog

Date Change
2026-11-16 Initial draft for 9.2.