> Portal Navigation:
> 
> - Append `.md` to any URL under `https://dev.wix.com/docs/` to get its markdown version.
> - Pages are either content pages (article or reference text) or menu pages (a list of links to child pages).
> - To get a menu page, truncate any URL to a parent path and append `.md` (e.g. `https://dev.wix.com/docs/sdk.md`, `https://dev.wix.com/docs/sdk/core-modules.md`).
> - Top-level index of all portals: https://dev.wix.com/docs/llms.txt
> - Full concatenated docs: https://dev.wix.com/docs/llms-full.txt

## Resource: Add Self-Managed App Tool Extensions with the SDK

## Article: Add Self-Managed App Tool Extensions with the SDK

## Article Link: https://dev.wix.com/docs/build-apps/develop-your-app/develop-a-self-managed-app/supported-extensions/backend-extensions/app-tools/add-self-managed-app-tool-extensions-with-the-sdk.md

## Article Content:

# Add Self-Managed App Tool Extensions with the SDK

Add an [App Tools extension](https://dev.wix.com/docs/build-apps/develop-your-app/extensions/backend-extensions/app-tools/about-app-tools-extensions.md) to your app to expose your app's capabilities to [Aria](https://dev.wix.com/docs/overview/ai-the-wix-platform/about-aria.md), Wix's AI assistant. After a Wix user installs your app, Aria can discover and invoke the tools your app declares, allowing Wix users to interact and perform actions with your app through natural language.

This article covers the SDK implementation. If you prefer a different approach, see:
- [Add Self-Managed App Tool Extensions with REST](https://dev.wix.com/docs/build-apps/develop-your-app/develop-a-self-managed-app/supported-extensions/backend-extensions/app-tools/add-self-managed-app-tool-extensions-with-rest.md)
- [Add App Tools Extensions with the CLI](https://dev.wix.com/docs/build-apps/develop-your-app/develop-an-app-with-the-cli/supported-extensions/backend/schema-plugins/add-app-tools-extensions-with-the-wix-cli.md)

Follow these steps to implement a self-managed app tools extension with the [Wix JavaScript SDK](https://dev.wix.com/docs/sdk.md):

## Step 1 | Add an App Tools extension

Declare the tools your app exposes to Aria in the [app dashboard](https://manage.wix.com/account/custom-apps).

To add an App Tools extension to your app:

1. Select an app from the [Custom Apps page](https://manage.wix.com/account/custom-apps) in your Wix Studio workspace.

1. On the **Extensions** page, click **+ Create Extension**.

   ![Create extension](https://wixmp-833713b177cebf373f611808.wixmp.com/images/72e71b0414df528b52e1b149f8b15114.png)

1. Search for **App Tools** and click **+ Create**.

1. In the JSON editor, configure your tools by referencing the **Documentation** panel on the right side of the page.

   ![App Tools extension JSON editor](https://wixmp-833713b177cebf373f611808.wixmp.com/images/e1bedd15e60134b733bb643b7ef7ca55.png)

  The following example configures a package tracking tool:

   ```json
   {
     "tools": [
       {
         "methodName": "getPackageTracking",
         "description": "Fetches the current tracking status of a package by its tracking number. Returns status, location, and estimated delivery date. Use when the Wix user wants to know where their package is or when it will arrive.",
         "requestSchema": {
           "type": "object",
           "required": ["trackingNumber"],
           "properties": {
             "trackingNumber": {
               "type": "string",
               "description": "The carrier tracking number for the package, for example '1Z999AA10123456784'."
             }
           }
         },
         "responseSchema": {
           "type": "object",
           "properties": {
             "trackingNumber": { "type": "string" },
             "status": { "type": "string" },
             "location": { "type": "string" },
             "estimatedDelivery": { "type": "string" }
           }
         },
         "activated": true
       }
     ]
   }
   ```

   > **Note:** Write `description` comprehensively. Aria reads it to decide when to call your tool. Be specific about what the tool does, when to use it, and what input it expects. Learn more about [effective tool descriptions](https://dev.wix.com/docs/build-apps/develop-your-app/extensions/backend-extensions/app-tools/about-app-tools-extensions.md#effective-tools). 

1. Click **Save**.

## Step 2 | Add a Tools Provider service plugin

Add a [Tools Provider service plugin](https://dev.wix.com/docs/api-reference/app-management/app-tools/tools-provider-v1/introduction.md) to your app. When Aria invokes one of your tools, Wix sends a `POST` request to `{baseUri}/v1/run-tool` on your server. In this plugin, you set `baseUri` to the URL where your app is hosted so Wix knows where to send that request.

To [add a Tools Provider service plugin](https://dev.wix.com/docs/build-apps/develop-your-app/develop-a-self-managed-app/supported-extensions/backend-extensions/service-plugins/add-self-managed-service-plugin-extensions-with-the-sdk.md):

1. On the **Extensions** page, click **+ Create Extension** again.

2. Search for **Tools Provider** and click **+ Create**.

3. In the JSON editor, set `baseUri` to the base URL where you host your app. Reference the **Documentation** panel for the full schema.

   ![Tools Provider service plugin JSON editor](https://wixmp-833713b177cebf373f611808.wixmp.com/images/0e60fdf754290c4fe7341f393f17b9f3.png)

4. Click **Save**.

## Step 3 | Retrieve your app's credentials

Retrieve the following:

- **App ID**: Required. Your app's unique identifier.
- **Public Key**: Required. Used to verify the authenticity of requests from Wix.
- **App Secret Key**: Only required if your [handler](#step-5--define-your-tool-handlers) calls Wix APIs.
- **Instance ID**: Only required if your [handler](#step-5--define-your-tool-handlers) calls Wix APIs. Identifies the [app instance](https://dev.wix.com/docs/build-apps/develop-your-app/auth/app-instances/about-app-instances.md) on the site that triggered the tool.

To retrieve your dashboard credentials:

1. In your [app dashboard](https://manage.wix.com/account/custom-apps), click the **More Actions** menu on the top right.
2. Select **View ID & Keys**.
3. Click **Show** and copy the **App ID** and **Public Key**. If your handler calls Wix APIs, also copy the **App Secret Key**.

There are several ways to retrieve an [app's instance ID](https://dev.wix.com/docs/build-apps/develop-your-app/auth/app-instances/about-app-instances.md). Learn more about [identifying the app instance in backend environments](https://dev.wix.com/docs/build-apps/develop-your-app/auth/app-instances/identify-the-app-instance-in-backend-environments.md#service-plugin-extension).

## Step 4 | Create a client

Import the Wix client and `toolsProvider` module in your app code. Then call [`createClient()`](https://dev.wix.com/docs/sdk/core-modules/sdk/wix-client.md) with the [`AppStrategy`](https://dev.wix.com/docs/sdk/core-modules/sdk/app-strategy.md) auth strategy and credentials you retrieved in step 3:

```js
import { createClient, AppStrategy } from '@wix/sdk';
import { toolsProvider } from '@wix/app-tools/service-plugins';

const wixClient = createClient({
  auth: AppStrategy({
    appId: <YOUR_APP_ID>,
    publicKey: <YOUR_PUBLIC_KEY>,
  }),
  modules: { toolsProvider },
});
```

## Step 5 | Define your tool handlers

Call `provideHandlers()` to register your tool logic. Wix calls `runTool` when Aria invokes one of your app's tools. Route on `methodName` to run the correct logic for each tool:

```js
wixClient.toolsProvider.provideHandlers({
  runTool: async ({ request }) => {
    const { methodName, payload } = request;

    switch (methodName) {
      case 'getPackageTracking': {
      
        const trackingNumber = payload?.trackingNumber;
        if (!trackingNumber) {
          throw new Error('trackingNumber is required');
        }

        // Look up the shipment in your system or call a 3rd-party API
        const shipment = await getShipmentByTrackingNumber(trackingNumber);

        return {
          response: {
            trackingNumber,
            status: shipment.status,
            location: shipment.location,
            estimatedDelivery: shipment.estimatedDelivery,
          },
        };
      }
      // Handle other tools here...
      default:
        throw new Error(`Unknown tool: ${methodName}`);
    }
  },
});
```

The [`runTool`](https://dev.wix.com/docs/api-reference/app-management/app-tools/tools-provider-v1/run-tool.md) handler receives the following:

- `request.methodName`: The name of the tool Aria is invoking.
- `request.payload`: The input the tool receives, matching the `requestSchema` configured in Step 1.

> **Note:** If your implementation returns an error or times out, Aria continues the conversation without the tool result.

## Step 6 | Expose a route

Define a route to handle `POST` requests from Wix.

In the route, call [`wixClient.servicePlugins.process()`](https://dev.wix.com/docs/sdk/core-modules/sdk/wix-client.md) and pass it the request URL and raw body. This method verifies and decodes the signed JWT, then routes the request to the handler you define with `provideHandlers()`.

> **Note:** Make sure to parse the body as text. Wix sends a signed JWT as a string, and the `process()` method verifies it. Common frameworks parse JSON bodies by default, which can cause errors when verifying using the `process()` method. 

The following exposes a route using Express: 
```js
app.post(
  '/*splat',
  express.text(),
  async (req, res) => {
    try {
      const result = await wixClient.servicePlugins.process({
        url: req.originalUrl,
        body: req.body,
      });
      res.json(result);
    } catch (err) {
      console.error('Tool call failed:', err);
      res.status(500).json({ error: err.message });
    }
  },
);
```

## Full code example

Here's a complete implementation for a `getPackageTracking` tool:

```js
import 'dotenv/config';
import express from 'express';
import { createClient, AppStrategy } from '@wix/sdk';
import { toolsProvider } from '@wix/app-tools/service-plugins';

const app = express();

const APP_ID = process.env.APP_ID;
const PUBLIC_KEY = process.env.PUBLIC_KEY;

const wixClient = createClient({
  auth: AppStrategy({
    appId: APP_ID,
    publicKey: PUBLIC_KEY,
  }),
  modules: { toolsProvider },
});

wixClient.toolsProvider.provideHandlers({
  runTool: async ({ request }) => {
    const { methodName, payload } = request;

    switch (methodName) {
      case 'getPackageTracking': {
        const trackingNumber = payload?.trackingNumber;
        if (!trackingNumber) {
          throw new Error('trackingNumber is required');
        }

        // Replace with your real tracking API call 
        const shipment = await getShipmentByTrackingNumber(trackingNumber);

        return {
          response: {
            trackingNumber,
            status: shipment.status,
            location: shipment.location,
            estimatedDelivery: shipment.estimatedDelivery,
          },
        };
      }
      default:
        throw new Error(`Unknown tool: ${methodName}`);
    }
  },
});

app.post(
  '/*splat',
  express.text(),
  async (req, res) => {
    try {
      const result = await wixClient.servicePlugins.process({
        url: req.originalUrl,
        body: req.body,
      });
      res.json(result);
    } catch (err) {
      console.error('Tool call failed:', err);
      res.status(500).json({ error: err.message });
    }
  },
);

app.listen(3000);
```


## See also

- [About Aria](https://dev.wix.com/docs/overview/ai-the-wix-platform/about-aria.md)
- [About App Tools extensions](https://dev.wix.com/docs/build-apps/develop-your-app/extensions/backend-extensions/app-tools/about-app-tools-extensions.md)
- [Authenticate Using OAuth](https://dev.wix.com/docs/build-apps/develop-your-app/auth/authenticate-using-oauth.md)
- [Add Self-Managed Service Plugin Extensions](https://dev.wix.com/docs/build-apps/develop-your-app/develop-a-self-managed-app/supported-extensions/backend-extensions/service-plugins/add-self-managed-service-plugin-extensions-with-the-sdk.md)