Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ For news and updates, [follow us on Threads](https://www.threads.com/@itsaplande
- A run starts on an @mention in a comment on an issue or a document, on an assignment, or on a
schedule. A schedule starts on a timer or when an issue moves to a state
- Tokens and cost of every run, by agent, project, and model
- Tools for other services: Notion, Baserow, Telegram, Slack, Threads, Instagram, Jina,
- Tools for other services: Notion, Baserow, Telegram, Slack, Threads, X, Instagram, Jina,
Firecrawl, Keenable, DataForSEO, Gitea, Forgejo, GitHub, and GitLab
- Images, video, music, and speech from the models on
[Kie](https://kie.ai?ref=0b6eb19939298accdf58e18b1a92a26e): Nano Banana, Seedream, Kling,
Expand Down
2 changes: 2 additions & 0 deletions packages/agent-tools/src/registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { firecrawl } from './tools/firecrawl';
import { telegram } from './tools/telegram';
import { slack } from './tools/slack';
import { threads } from './tools/threads';
import { x } from './tools/x';
import { instagram } from './tools/instagram';
import { notion } from './tools/notion';
import { baserow } from './tools/baserow';
Expand All @@ -33,6 +34,7 @@ export const INTEGRATIONS: Integration[] = [
telegram,
slack,
threads,
x,
instagram,
notion,
baserow,
Expand Down
163 changes: 163 additions & 0 deletions packages/agent-tools/src/tools/x/__tests__/x.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
import { afterAll, afterEach, beforeEach, describe, expect, it, mock, spyOn } from 'bun:test';
import { ResponseTooLargeError, UrlNotAllowedError } from '@repo/net';

const pinnedFetch = mock(
async (_url: string) => new Response('png-bytes', { headers: { 'content-type': 'image/png' } }),
);
mock.module('@repo/net', () => ({ pinnedFetch, ResponseTooLargeError, UrlNotAllowedError }));

const { getTool } = await import('../../../registry');
const { authorization } = await import('../client');
const { xPost } = await import('../post');
const { xSearch } = await import('../search');
const { xGetPost } = await import('../get-post');
const { verifyX } = await import('../verify');
const { xLike } = await import('../interactions');
const { xHomeTimeline } = await import('../timelines');

const fetchSpy = spyOn(globalThis, 'fetch');
const credential = {
apiKey: 'ck',
apiKeySecret: 'cs',
accessToken: 'at',
accessTokenSecret: 'ats',
};

function calls() {
return fetchSpy.mock.calls.map(([url, init]) => ({
url: String(url),
init: init as RequestInit & { headers: Record<string, string> },
}));
}

describe('x', () => {
beforeEach(() => pinnedFetch.mockClear());
afterEach(() => fetchSpy.mockReset());
afterAll(() => fetchSpy.mockRestore());

it('is registered with four secret fields', () => {
const integration = getTool('x_post')?.integration;
expect(integration?.key).toBe('x');
expect(integration?.credentialSchema.map((f) => [f.key, f.type])).toEqual([
['apiKey', 'secret'],
['apiKeySecret', 'secret'],
['accessToken', 'secret'],
['accessTokenSecret', 'secret'],
]);
});

// The worked example of X's "Creating a signature" guide.
it('signs a request as the OAuth 1.0a guide does', () => {
const header = authorization(
{
apiKey: 'xvz1evFS4wEEPTGEFPHBog',
apiKeySecret: 'kAcSOqF21Fu85e7zjz7ZN2U4ZRhfV3WpwPAoE3Z7kBw',
accessToken: '370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb',
accessTokenSecret: 'LswwdoUaIvS8ltyTt5jkRh4J50vUPVVHtR2YPi5kE',
},
'POST',
'https://api.twitter.com/1.1/statuses/update.json',
[
['status', 'Hello Ladies + Gentlemen, a signed OAuth request!'],
['include_entities', 'true'],
],
{ nonce: 'kYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg', timestamp: 1318622958 },
);
expect(header).toContain('oauth_signature="hCtSmYh%2BiHYCEqBWrE7C7hYmtUk%3D"');
});

it('uploads each image, then posts a reply with their media ids', async () => {
fetchSpy
.mockResolvedValueOnce(Response.json({ data: { id: 'm1' } }))
.mockResolvedValueOnce(
Response.json({ data: { id: '42', text: 'Shipped' } }, { status: 201 }),
);
const result = await xPost.execute(credential, {
text: 'Shipped',
imageUrls: ['https://cdn.example.com/a.png'],
replyToId: '7',
});

expect(pinnedFetch.mock.calls[0]?.[0]).toBe('https://cdn.example.com/a.png');
const [upload, post] = calls();
expect(upload?.url).toBe('https://api.x.com/2/media/upload');
const form = upload?.init.body as FormData;
expect(form.get('media_category')).toBe('tweet_image');
expect(form.get('media')).toBeInstanceOf(Blob);
expect(post?.url).toBe('https://api.x.com/2/tweets');
expect(post?.init.headers.Authorization).toStartWith('OAuth oauth_consumer_key="ck"');
expect(JSON.parse(String(post?.init.body))).toEqual({
text: 'Shipped',
media: { media_ids: ['m1'] },
reply: { in_reply_to_tweet_id: '7' },
});
expect(result).toEqual({ id: '42', text: 'Shipped', url: 'https://x.com/i/status/42' });
});

it('encodes query values by RFC 3986 and sends start_time without milliseconds', async () => {
fetchSpy.mockResolvedValueOnce(Response.json({ meta: { result_count: 0 } }));
const result = await xSearch.execute(credential, {
query: 'from:me (a) b',
startTime: '2026-11-25',
});

const url = new URL(calls()[0]!.url);
expect(url.search).toContain('query=from%3Ame%20%28a%29%20b');
expect(url.searchParams.get('start_time')).toBe('2026-11-25T00:00:00Z');
expect(result).toEqual({ data: [], includes: null, meta: { result_count: 0 } });
});

it('fails with the detail X sends, also on a 200 with no data', async () => {
fetchSpy.mockResolvedValueOnce(
Response.json({
errors: [{ title: 'Not Found Error', detail: 'Could not find post with id: [9].' }],
}),
);
await expect(xGetPost.execute(credential, { postId: '9' })).rejects.toThrow(
'X API error (200): Could not find post with id: [9].',
);
});

it('likes as the account the credential acts as, and undoes the like', async () => {
fetchSpy
.mockResolvedValueOnce(Response.json({ data: { id: '5' } }))
.mockResolvedValueOnce(Response.json({ data: { liked: true } }))
.mockResolvedValueOnce(Response.json({ data: { id: '5' } }))
.mockResolvedValueOnce(Response.json({ data: { liked: false } }));
expect(await xLike.execute(credential, { postId: '42' })).toEqual({
postId: '42',
liked: true,
});
expect(await xLike.execute(credential, { postId: '42', undo: true })).toEqual({
postId: '42',
liked: false,
});

const [, like, , unlike] = calls();
expect(like?.url).toBe('https://api.x.com/2/users/5/likes');
expect(JSON.parse(String(like?.init.body))).toEqual({ tweet_id: '42' });
expect([unlike?.init.method, unlike?.url]).toEqual([
'DELETE',
'https://api.x.com/2/users/5/likes/42',
]);
});

it('reads the home timeline of the own account without the left-out kinds', async () => {
fetchSpy
.mockResolvedValueOnce(Response.json({ data: { id: '5' } }))
.mockResolvedValueOnce(Response.json({ data: [{ id: '1', text: 'hi' }], meta: {} }));
const result = await xHomeTimeline.execute(credential, { exclude: ['replies', 'retweets'] });

const url = new URL(calls()[1]!.url);
expect(url.pathname).toBe('/2/users/5/timelines/reverse_chronological');
expect(url.searchParams.get('exclude')).toBe('replies,retweets');
expect(result).toMatchObject({ data: [{ id: '1', text: 'hi' }] });
});

it('rejects a credential X answers 401 to', async () => {
fetchSpy.mockResolvedValueOnce(Response.json({ title: 'Unauthorized' }, { status: 401 }));
expect(await verifyX(credential, AbortSignal.timeout(1000))).toBe('rejected');
fetchSpy.mockResolvedValueOnce(Response.json({ data: { id: '1' } }));
expect(await verifyX(credential, AbortSignal.timeout(1000))).toBe('valid');
});
});
135 changes: 135 additions & 0 deletions packages/agent-tools/src/tools/x/client.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
import { createHmac, randomBytes } from 'node:crypto';
import type { ToolConfig } from '../../types';
import { timeFilter, toUnixSeconds } from '../time';

// X API v2. A credential is the app's key pair plus the access token pair of one account,
// for OAuth 1.0a: those tokens do not expire, while an OAuth 2.0 user token lasts two hours.
export const X_BASE = 'https://api.x.com/2';

// RFC 3986, which OAuth 1.0a signs with: encodeURIComponent leaves !'()* unencoded.
function pct(s: string): string {
return encodeURIComponent(s).replace(
/[!'()*]/g,
(c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`,
);
}

function compare(a: string, b: string): number {
if (a === b) return 0;
return a < b ? -1 : 1;
}

// The signature covers the method, the address and the query parameters. A JSON or
// multipart body is not signed.
export function authorization(
credential: ToolConfig,
method: string,
url: string,
params: [string, string][] = [],
oauth = { nonce: randomBytes(16).toString('hex'), timestamp: Math.floor(Date.now() / 1000) },
): string {
const fields: Record<string, string> = {
oauth_consumer_key: String(credential.apiKey ?? ''),
oauth_nonce: oauth.nonce,
oauth_signature_method: 'HMAC-SHA1',
oauth_timestamp: String(oauth.timestamp),
oauth_token: String(credential.accessToken ?? ''),
oauth_version: '1.0',
};
const pairs = [...params, ...Object.entries(fields)].map(([k, v]) => [pct(k), pct(v)]);
pairs.sort(([ak, av], [bk, bv]) => compare(ak, bk) || compare(av, bv));
const base = [method, pct(url), pct(pairs.map(([k, v]) => `${k}=${v}`).join('&'))].join('&');
const key = `${pct(String(credential.apiKeySecret ?? ''))}&${pct(String(credential.accessTokenSecret ?? ''))}`;
const signature = createHmac('sha1', key).update(base).digest('base64');
Comment thread
croffasia marked this conversation as resolved.
Dismissed
return `OAuth ${Object.entries({ ...fields, oauth_signature: signature })
.map(([k, v]) => `${k}="${pct(v)}"`)
.join(', ')}`;
}

type XProblem = { title?: string; detail?: string; message?: string };

export interface XResponse<T = unknown> {
data?: T;
includes?: unknown;
meta?: Record<string, unknown>;
errors?: XProblem[];
}

// A lookup of a missing or deleted post answers 200 with errors and no data, so that is
// a failure too.
export async function xRequest<T = unknown>(
credential: ToolConfig,
method: 'GET' | 'POST' | 'DELETE',
path: string,
opts: {
query?: Record<string, string | number | undefined>;
json?: unknown;
form?: FormData;
} = {},
): Promise<XResponse<T>> {
const url = `${X_BASE}/${path}`;
const params = Object.entries(opts.query ?? {})
.filter(([, v]) => v !== undefined && v !== '')
.map(([k, v]): [string, string] => [k, String(v)]);
const query = params.map(([k, v]) => `${pct(k)}=${pct(v)}`).join('&');
const headers: Record<string, string> = {
Authorization: authorization(credential, method, url, params),
};
let body: string | FormData | undefined = opts.form;
if (opts.json !== undefined) {
headers['Content-Type'] = 'application/json';
body = JSON.stringify(opts.json);
}
const res = await fetch(query ? `${url}?${query}` : url, { method, headers, body });
const raw = await res.text();
let parsed: XResponse<T> & XProblem = {};
try {
parsed = raw ? JSON.parse(raw) : {};
} catch {
/* non-JSON error page */
}
let problem: XProblem | undefined;
if (!res.ok) problem = parsed.errors?.[0] ?? parsed;
else if (parsed.data === undefined) problem = parsed.errors?.[0];
if (problem) {
const msg = problem.detail || problem.message || problem.title || raw.slice(0, 300);
throw new Error(`X API error (${res.status})${msg ? `: ${msg}` : ''}`);
}
return parsed;
}

export async function myId(credential: ToolConfig): Promise<string> {
const body = await xRequest<{ id: string }>(credential, 'GET', 'users/me');
return String(body.data?.id);
}

// The author is expanded so a result names who wrote each post.
export const POST_QUERY = {
'post.fields': 'created_at,conversation_id,public_metrics',
expansions: 'author_id',
'user.fields': 'username,name',
};

export const USER_FIELDS =
'description,location,url,created_at,verified,public_metrics,profile_image_url';

export function page(body: XResponse) {
return { data: body.data ?? [], includes: body.includes ?? null, meta: body.meta ?? null };
}

export function usernamePath(username: unknown): string {
return `users/by/username/${encodeURIComponent(String(username).replace(/^@/, ''))}`;
}

// A second describe() replaces the first, so each field gets its whole text here.
export function timeInput(meaning: string) {
return timeFilter
.optional()
.describe(`${meaning} A date like "2026-06-14", an ISO time, or a unix timestamp in seconds.`);
}

// X takes RFC 3339 times without milliseconds.
export function isoTime(v: unknown): string | undefined {
const s = toUnixSeconds(v as number | string | undefined);
return s === undefined ? undefined : new Date(s * 1000).toISOString().replace('.000Z', 'Z');
}
18 changes: 18 additions & 0 deletions packages/agent-tools/src/tools/x/delete.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { z } from 'zod';
import type { CustomToolEntry } from '../../types';
import { xRequest } from './client';

export const xDeletePost: CustomToolEntry = {
key: 'x_delete_post',
group: 'Publishing',
label: 'X Delete Post',
description: 'Delete one of your own posts or replies on X by its id.',
inputSchema: z.object({
postId: z.string().min(1).describe('Id of the post to delete.'),
}),
execute: async (credential, input) => {
const postId = String(input.postId);
await xRequest(credential, 'DELETE', `tweets/${encodeURIComponent(postId)}`);
return { deleted: true, postId };
},
};
23 changes: 23 additions & 0 deletions packages/agent-tools/src/tools/x/get-post.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { z } from 'zod';
import type { CustomToolEntry } from '../../types';
import { POST_QUERY, xRequest } from './client';

export const xGetPost: CustomToolEntry = {
key: 'x_get_post',
group: 'Posts and profiles',
label: 'X Get Post',
description:
'Get a post on X by its id: text, author, time, conversation id and like, repost and reply counts.',
inputSchema: z.object({
postId: z.string().min(1).describe('Id of the post, the number at the end of its URL.'),
}),
execute: async (credential, input) => {
const { data, includes } = await xRequest(
credential,
'GET',
`tweets/${encodeURIComponent(String(input.postId))}`,
{ query: POST_QUERY },
);
return { data, includes: includes ?? null };
},
};
6 changes: 6 additions & 0 deletions packages/agent-tools/src/tools/x/icon.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import type { IntegrationIcon } from '../../types';

// From Simple Icons (CC0). The mark is black, so it takes the text color.
export const xIcon: IntegrationIcon = {
path: 'M18.901 1.153h3.68l-8.04 9.19L24 22.846h-7.406l-5.8-7.584-6.638 7.584H.474l8.6-9.83L0 1.154h7.594l5.243 6.932ZM17.61 20.644h2.039L6.486 3.24H4.298Z',
};
Loading
Loading