#### TypeScript SDK

# Tools

Define functions your code runs, let the model write shell commands, and add the built-in tools that SpaceXSI runs during a response. Examples use the `client` created in the [quickstart](/developers/sdk/typescript#quickstart).

## Function calling

Describe custom functions with JSON Schema, run the requested function in your application, and send its result back to the model. See the [Function Calling guide](/developers/tools/function-calling) for details.

```typescript
import { type InputItem, type Tool, isFunctionCall, Grok } from '@grok/sdk';

const client = new Grok();
const prompt = 'What is the weather in San Francisco?';
const input: Array<InputItem> = [{ role: 'user', content: prompt }];
const getWeatherTool: Tool = {
  type: 'function',
  name: 'get_weather',
  description: 'Get the current weather for a location.',
  parameters: {
    type: 'object',
    properties: {
      location: { type: 'string' },
    },
    required: ['location'],
    additionalProperties: false,
  },
};

async function getWeather(args: unknown) {
  if (
    typeof args !== 'object' ||
    args === null ||
    !('location' in args) ||
    typeof args.location !== 'string'
  ) {
    throw new Error('get_weather expects a location string');
  }
  return { location: args.location, temperatureC: 18, conditions: 'sunny' };
}

const response = await client.responses.create({
  model: 'grok-4.7',
  input,
  parallel_tool_calls: false,
  tools: [getWeatherTool],
});

const call = response.output.find(isFunctionCall);
if (!call) throw new Error('The model did not call get_weather');
const result = await getWeather(JSON.parse(call.arguments));

const answer = await client.responses.create({
  model: 'grok-4.7',
  input: [
    ...input,
    ...response.toInput(),
    { type: 'function_call_output', call_id: call.call_id, output: JSON.stringify(result) },
  ],
});

console.log(answer.toText());
```

`parallel_tool_calls: false` limits the model to one function call per turn. By default, the model can request several calls at once, which the [tool call loop](#tool-call-loop) handles.

Treat function names and arguments as untrusted input. Only dispatch explicitly allowed functions, and validate arguments before running them.

### Tool call loop

To let the model call tools across multiple turns until it produces a final answer, run a bounded loop. Stream each turn, start each function call as soon as its arguments complete, and pass the outputs back alongside `response.toInput()`. Stop when a turn produces no function calls, and cap the turn count to avoid unbounded loops. This example continues the one above and reuses its `client`, `getWeatherTool`, and `getWeather`:

```typescript
import { type FunctionToolCall } from '@grok/sdk';

const tools: Array<Tool> = [getWeatherTool];
const handlers: Record<string, (args: unknown) => Promise<unknown>> = {
  get_weather: getWeather,
};

async function runTool(call: FunctionToolCall): Promise<InputItem> {
  let output: unknown;
  try {
    const handler = handlers[call.name];
    if (!handler) throw new Error(`Unknown tool: ${call.name}`);
    output = await handler(JSON.parse(call.arguments));
  } catch (err) {
    output = { error: err instanceof Error ? err.message : String(err) };
  }
  return {
    type: 'function_call_output',
    call_id: call.call_id,
    output: JSON.stringify(output),
  };
}

const loopInput: Array<InputItem> = [
  { role: 'user', content: 'Compare the weather in Paris and Tokyo.' },
];

for (let turn = 0; turn < 10; turn++) {
  const toolRuns: Array<Promise<InputItem>> = [];
  const stream = await client.responses.create({
    model: 'grok-4.7',
    input: loopInput,
    tools,
    stream: true,
  });
  const response = await stream
    .on('text', text => process.stdout.write(text))
    .on('client_tool_call', call => {
      if (call.type === 'function_call') toolRuns.push(runTool(call));
    })
    .done();
  if (toolRuns.length === 0) break;

  const toolOutputs = await Promise.all(toolRuns);
  loopInput.push(...response.toInput(), ...toolOutputs);
}
```

The `handlers` map restricts which functions the model can call. `runTool()` returns errors as tool output rather than throwing, so the model can recover and a failed tool call does not abort an active stream.

## Shell commands

With the `shell` tool, the model generates shell commands and your application executes them. Each call arrives via the `'client_tool_call'` listener as a `shell_call` with commands in `action.commands`. Because the model writes these commands, run them in a sandbox or container, or validate every command before execution:

```typescript
import { execFile } from 'node:child_process';
import { Grok } from '@grok/sdk';

const client = new Grok();
const allowedPrograms = new Set(['df', 'du']);

const stream = await client.responses.create({
  model: 'grok-4.7',
  input: 'How much free disk space does this machine have?',
  tools: [{ type: 'shell', environment: { type: 'local' } }],
  stream: true,
});

await stream
  .on('client_tool_call', call => {
    if (call.type === 'shell_call') {
      for (const command of call.action.commands) {
        const [program, ...args] = command.trim().split(/\s+/);
        if (!program || !allowedPrograms.has(program)) {
          console.warn(`Skipped command: ${command}`);
          continue;
        }
        execFile(program, args, (_error, stdout, stderr) => console.log(stdout || stderr));
      }
    }
  })
  .done();
```

To feed command results back into the conversation, include a `shell_call_output` item in the next request: `{ type: 'shell_call_output', call_id: call.call_id, output: [{ stdout, stderr, outcome: { type: 'exit', exit_code: 0 } }] }`.

You can also attach skills in the tool's `environment`. A skill is a directory containing a `SKILL.md` file of instructions. The model sees each skill's name and description, reads its `SKILL.md` through your shell tool when relevant, and follows those instructions. If your runner restricts allowed commands, permit reading the skill directory:

```typescript
const shell: Tool = {
  type: 'shell',
  environment: {
    type: 'local',
    skills: [
      {
        name: 'release-notes',
        description: "Write release notes from this repo's git log in our house style.",
        path: './skills/release-notes',
      },
    ],
  },
};
```

## Built-in tools

In addition to client-side `function` and `shell` tools, the API includes server-side built-in tools that SpaceXSI executes during the response. Construct them with typed helpers from `@grok/sdk/tools`:

* `webSearch()` (`web_search`) — searches the web; options include `allowed_domains`, `excluded_domains`, and `user_location`
* `xSearch()` (`x_search`) — searches posts on X; options include `allowed_x_handles`, `excluded_x_handles`, `from_date`, and `to_date`
* `codeExecution()` (`code_interpreter`) — writes and runs Python code in a sandbox
* `collectionsSearch()` (`file_search`) — searches [collections](/developers/files/collections) listed in `vector_store_ids`
* `imageGeneration()` (`image_generation`) — creates or edits images within a response
* `mcp()` (`mcp`) — invokes tools on a remote MCP server at `server_url`, identified by `server_label`

Each helper returns a plain tool object, so you can also write `{ type: 'web_search' }` directly. The `Tool` type autocompletes known tool types and accepts newer types released after your SDK version, though only the helpers validate each tool's options. See [Tools Overview](/developers/tools/overview) for full option details.

### Web search

Add `webSearch()` when a prompt needs current web information (see [Web Search](/developers/tools/web-search) for all options):

```typescript
import { Grok } from '@grok/sdk';
import { webSearch } from '@grok/sdk/tools';

const client = new Grok();

const response = await client.responses.create({
  model: 'grok-4.7',
  input: 'What are the latest developments in commercial spaceflight?',
  tools: [webSearch()],
});

console.log(response.toText());
console.log(response.usage.num_server_side_tools_used);
```

### X search

Search posts on X, optionally filtered by handles and date range (see [X Search](/developers/tools/x-search) for all options):

```typescript
import { xSearch } from '@grok/sdk/tools';

const response = await client.responses.create({
  model: 'grok-4.7',
  input: 'What has SpaceXSI announced on X since September 2026?',
  tools: [xSearch({ allowed_x_handles: ['xai'], from_date: '2026-09-01' })],
});
```

`allowed_x_handles` and `excluded_x_handles` each accept up to 20 handles and cannot be combined. Set `enable_image_understanding` or `enable_video_understanding` to let the model inspect media in posts.

`to_date` is exclusive, so a single day spans from that date to the next (`xSearch({ from_date: '2026-10-01', to_date: '2026-10-02' })`). When dates are omitted, the model selects the range to search.

When streaming, each finished X search arrives in the `'server_tool_call'` listener as a `custom_tool_call` whose `name` is the search executed (such as `x_keyword_search`) and whose `input` is a JSON string of search arguments:

```typescript
await stream
  .on('server_tool_call', call => {
    if (call.type === 'custom_tool_call') console.log(call.name, call.input);
  })
  .done();
```

### Code execution

Let the model write and execute Python in a sandbox for calculations and data analysis (see [Code Execution](/developers/tools/code-execution)):

```typescript
import { codeExecution } from '@grok/sdk/tools';

const response = await client.responses.create({
  model: 'grok-4.7',
  input: 'What is the standard deviation of 12, 15, 19, 22, and 31?',
  tools: [codeExecution()],
});
```

The sandbox ships with common Python libraries installed, and `codeExecution()` takes no options.

### Collections search

Search documents indexed in [collections](/developers/files/collections) (see [Collections Search](/developers/tools/collections-search)):

```typescript
import { collectionsSearch } from '@grok/sdk/tools';

const response = await client.responses.create({
  model: 'grok-4.7',
  input: 'What does our refund policy say about digital purchases?',
  tools: [collectionsSearch({ vector_store_ids: ['your-collection-id'], max_num_results: 10 })],
});
```

### Remote MCP servers

Connect the model to a [remote MCP server](/developers/tools/remote-mcp) that SpaceXSI calls during generation:

```typescript
import { mcp } from '@grok/sdk/tools';

const response = await client.responses.create({
  model: 'grok-4.7',
  input: 'What is the modelcontextprotocol/typescript-sdk repository for?',
  tools: [mcp({ server_url: 'https://mcp.deepwiki.com/mcp', server_label: 'deepwiki' })],
});
```

The server must use Streamable HTTP or SSE transport. Restrict access to specific tools with `allowed_tools`, and pass credentials with `authorization` or `headers`. `require_approval` and `connector_id` are not supported yet.

### Image generation tool

Use `imageGeneration()` to let the model create or edit images as part of a response (see [Image Generation](/developers/tools/image-generation)). Generated images arrive as `image_generation_call` output items with base64 data in `result`:

```typescript
import { writeFile } from 'node:fs/promises';
import { isImageGenerationCall, Grok } from '@grok/sdk';
import { imageGeneration } from '@grok/sdk/tools';

const client = new Grok();

const response = await client.responses.create({
  model: 'grok-4.7',
  input:
    'Generate an image of a corgi surfing a big wave, in the style of a Japanese woodblock print.',
  tools: [imageGeneration()],
});

console.log(response.toText());

const call = response.output.find(isImageGenerationCall);
if (call?.result) {
  await writeFile('corgi.jpg', Buffer.from(call.result, 'base64'));
}
```

Pass `action: 'generate'` or `action: 'edit'` to `imageGeneration()` to restrict which action the model may take. When streaming, each call emits `response.image_generation_call.in_progress`, `response.image_generation_call.generating`, and `response.image_generation_call.completed`, followed by a `response.output_item.done` event carrying the completed item.

For direct control over aspect ratio, resolution, batch count, and output format, use the [image generation](/developers/sdk/typescript/images-and-video#image-generation) and [image editing](/developers/sdk/typescript/images-and-video#image-editing) methods instead.
