--- title: "Build an Agent That Connects to the MCP Server" slug: "build-an-agent-that-connects-to-the-mcp-server" description: "Please provide the article content." status: "new" updated: 2026-11-17T17:32:42Z published: 2026-11-17T17:32:42Z canonical: "docs.unqork.io/build-an-agent-that-connects-to-the-mcp-server" --- > ## Documentation Index > Fetch the complete documentation index at: https://docs.unqork.io/llms.txt > Use this file to discover all available pages before exploring further. # Build an Agent That Connects to the MCP Server > [!WARNING] > 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. > [!NOTE] > 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](/unqorkai/docs/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](/unqorkai/docs/publish-api-modules-as-mcp-tools#create-the-agents-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](/unqorkai/docs/publish-api-modules-as-mcp-tools#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](/unqorkai/docs/publish-api-modules-as-mcp-tools#connect-a-client). 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](/unqorkai/docs/publish-api-modules-as-mcp-tools#get-a-token). ```js 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](/unqorkai/docs/publish-api-modules-as-mcp-tools#test-the-endpoint-with-postman). ## 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. ```js 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](/unqorkai/docs/mcp-server-for-api-modules#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. ```js // 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. ```js 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](/unqorkai/docs/mcp-server-for-api-modules#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](/unqorkai/docs/mcp-server-for-api-modules#tool-settings). - **More environments**: Move the agent from a test environment to production with the steps in [Set Up the Agent in Another Environment](/unqorkai/docs/publish-api-modules-as-mcp-tools#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. | A functionality of a software. For example, Copy and Paste is a feature of a computer's operating system. A definition An API endpoint is the location where an API receives requests for a specific resource on its server. It's the point of contact between an API client and an API server, and is usually a uniform resource locator (URL) that provides the location of the resource. APIs (application programming interfaces) are a set of protocols and definitions developers use to build and integrate application software. APIs act as the connective tissue between products and services. The Unqork front-end application framework that delivers Creator-built applications to end-users. Express is the layer end-users interact with—the published forms, screens, and navigation built in the Module Builder. Express is distinct from Express View, which is a Creator-facing preview tool in the IDE. The client secret is a secret known only to the application and the authorization server. The client secret acts as the applications password to the server. Authentication secrets are a value of confidential information. For example, a password, security token, or cryptographic key, that is used to verify a user's identity during the authentication process to grant access to a system or application. HTTP (Hypertext Transfer Protocol) is an application-layer protocol used to transmit hypermedia documents like HTML. The client_id is a public identifier for apps APIs (application programming interfaces) are a set of protocols and definitions developers use to build and integrate application software. APIs act as the connective tissue between products and services. JSON (JavaScript Object Notation) is an open standard file and data interchange format. Unqork uses JSON for submission (record) data. Enter outputs components and actions you want the component to perform. A key-value pair is a fundamental data structure where a unique "key" is associated with a specific "value," used for organizing and retrieving data efficiently, like in dictionaries or databases.