Skip to content

πŸ“¨ The ultimate agentic social media scheduling tool πŸ€–

feat: tools in public api

Nevo Davidaf08ae118703
diff --git a/apps/backend/src/public-api/routes/v1/public.integrations.controller.ts b/apps/backend/src/public-api/routes/v1/public.integrations.controller.ts
index 03667e674..ac8b12db5 100644
--- a/apps/backend/src/public-api/routes/v1/public.integrations.controller.ts
+++ b/apps/backend/src/public-api/routes/v1/public.integrations.controller.ts
@@ -33,9 +33,11 @@ import axios from 'axios';
import { Readable } from 'stream';
import { lookup } from 'mime-types';
import * as Sentry from '@sentry/nestjs';
-import { checkAuth } from '@gitroom/nestjs-libraries/chat/auth.context';
-import { socialIntegrationList } from '@gitroom/nestjs-libraries/integrations/integration.manager';
+import { socialIntegrationList, IntegrationManager } from '@gitroom/nestjs-libraries/integrations/integration.manager';
import { getValidationSchemas } from '@gitroom/nestjs-libraries/chat/validation.schemas.helper';
+import { RefreshIntegrationService } from '@gitroom/nestjs-libraries/integrations/refresh.integration.service';
+import { RefreshToken } from '@gitroom/nestjs-libraries/integrations/social.abstract';
+import { timer } from '@gitroom/helpers/utils/timer';
@ApiTags('Public API')
@Controller('/public/v1')
@@ -46,7 +48,9 @@ export class PublicIntegrationsController {
private _integrationService: IntegrationService,
private _postsService: PostsService,
private _mediaService: MediaService,
- private _notificationService: NotificationService
+ private _notificationService: NotificationService,
+ private _integrationManager: IntegrationManager,
+ private _refreshIntegrationService: RefreshIntegrationService
) {}
@Post('/upload')
@@ -222,6 +226,7 @@ export class PublicIntegrationsController {
@GetOrgFromRequest() org: Organization,
@Param('id') id: string
) {
+ Sentry.metrics.count('public_api-request', 1);
const loadIntegration = await this._integrationService.getIntegrationById(
org.id,
id
@@ -246,12 +251,97 @@ export class PublicIntegrationsController {
const schemas = !integration.dto
? false
: getValidationSchemas()[integration.dto.name];
+ const tools = this._integrationManager.getAllTools();
+ const rules = this._integrationManager.getAllRulesDescription();
return {
output: {
+ rules: rules[integration.identifier],
maxLength,
settings: !schemas ? 'No additional settings required' : schemas,
+ tools: tools[integration.identifier],
},
};
}
+
+ @Post('/integration-trigger/:id')
+ async triggerIntegrationTool(
+ @GetOrgFromRequest() org: Organization,
+ @Param('id') id: string,
+ @Body() body: { methodName: string; data: Record<string, string> }
+ ) {
+ Sentry.metrics.count('public_api-request', 1);
+ const getIntegration = await this._integrationService.getIntegrationById(
+ org.id,
+ id
+ );
+
+ if (!getIntegration) {
+ throw new HttpException({ msg: 'Integration not found' }, 404);
+ }
+
+ const integrationProvider = socialIntegrationList.find(
+ (p) => p.identifier === getIntegration.providerIdentifier
+ )!;
+
+ if (!integrationProvider) {
+ throw new HttpException({ msg: 'Integration provider not found' }, 404);
+ }
+
+ const tools = this._integrationManager.getAllTools();
+ if (
+ // @ts-ignore
+ !tools[integrationProvider.identifier]?.some(
+ (p: any) => p.methodName === body.methodName
+ ) ||
+ // @ts-ignore
+ !integrationProvider[body.methodName]
+ ) {
+ throw new HttpException({ msg: 'Tool not found' }, 404);
+ }
+
+ while (true) {
+ try {
+ // @ts-ignore
+ const result = await integrationProvider[body.methodName](
+ getIntegration.token,
+ body.data || {},
+ getIntegration.internalId,
+ getIntegration
+ );
+
+ return { output: result };
+ } catch (err) {
+ if (err instanceof RefreshToken) {
+ const data = await this._refreshIntegrationService.refresh(
+ getIntegration
+ );
+
+ if (!data) {
+ await this._integrationService.disconnectChannel(
+ org.id,
+ getIntegration
+ );
+ throw new HttpException(
+ { msg: 'Channel disconnected due to expired token' },
+ 401
+ );
+ }
+
+ const { accessToken } = data;
+
+ if (accessToken) {
+ getIntegration.token = accessToken;
+
+ if (integrationProvider.refreshWait) {
+ await timer(10000);
+ }
+
+ continue;
+ }
+ }
+ throw new HttpException({ msg: 'Unexpected error' }, 500);
+ }
+ }
+ }
}
diff --git a/apps/cli/INTEGRATION_TOOLS_WORKFLOW.md b/apps/cli/INTEGRATION_TOOLS_WORKFLOW.md
new file mode 100644
index 000000000..e6986e5de
--- /dev/null
+++ b/apps/cli/INTEGRATION_TOOLS_WORKFLOW.md
@@ -0,0 +1,435 @@
+# Integration Tools Workflow
+
+Some integrations require additional data (like IDs, tags, playlists, etc.) before you can post. The CLI supports a complete workflow to discover and use these tools.
+
+## The Complete Workflow
+
+### Step 1: List Integrations
+
+```bash
+postiz integrations:list
+```
+
+Get your integration IDs.
+
+### Step 2: Get Integration Settings
+
+```bash
+postiz integrations:settings <integration-id>
+```
+
+This returns:
+- `maxLength` - Character limit
+- `settings` - Required/optional fields
+- **`tools`** - Callable methods to fetch additional data
+
+### Step 3: Trigger Tools (If Needed)
+
+If settings require IDs/data you don't have, use the tools:
+
+```bash
+postiz integrations:trigger <integration-id> <method-name> -d '{"key":"value"}'
+```
+
+### Step 4: Create Post with Complete Settings
+
+Use the data from Step 3 in your post settings.
+
+## Real-World Example: Reddit
+
+### 1. Get Reddit Integration Settings
+
+```bash
+postiz integrations:settings reddit-abc123
+```
+
+**Output:**
+```json
+{
+ "output": {
+ "maxLength": 40000,
+ "settings": {
+ "properties": {
+ "subreddit": {
+ "type": "array",
+ "items": {
+ "properties": {
+ "subreddit": { "type": "string" },
+ "title": { "type": "string" },
+ "flair": {
+ "properties": {
+ "id": { "type": "string" } // ← Need flair ID!
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "tools": [
+ {
+ "methodName": "getFlairs",
+ "description": "Get available flairs for a subreddit",
+ "dataSchema": [
+ {
+ "key": "subreddit",
+ "description": "The subreddit name",
+ "type": "string"
+ }
+ ]
+ },
+ {
+ "methodName": "searchSubreddits",
+ "description": "Search for subreddits",
+ "dataSchema": [
+ {
+ "key": "query",
+ "description": "Search query",
+ "type": "string"
+ }
+ ]
+ }
+ ]
+ }
+}
+```
+
+### 2. Get Flairs for the Subreddit
+
+```bash
+postiz integrations:trigger reddit-abc123 getFlairs -d '{"subreddit":"programming"}'
+```
+
+**Output:**
+```json
+{
+ "output": [
+ {
+ "id": "flair-12345",
+ "name": "Discussion"
+ },
+ {
+ "id": "flair-67890",
+ "name": "Tutorial"
+ }
+ ]
+}
+```
+
+### 3. Create Post with Flair ID
+
+```bash
+postiz posts:create \
+ -c "Check out my project!" \
+ -p reddit \
+ --settings '{
+ "subreddit": [{
+ "value": {
+ "subreddit": "programming",
+ "title": "My Cool Project",
+ "type": "text",
+ "url": "",
+ "is_flair_required": true,
+ "flair": {
+ "id": "flair-12345",
+ "name": "Discussion"
+ }
+ }
+ }]
+ }' \
+ -i "reddit-abc123"
+```
+
+## Example: YouTube Playlists
+
+### 1. Get YouTube Settings
+
+```bash
+postiz integrations:settings youtube-123
+```
+
+**Output includes tools:**
+```json
+{
+ "tools": [
+ {
+ "methodName": "getPlaylists",
+ "description": "Get your YouTube playlists",
+ "dataSchema": []
+ },
+ {
+ "methodName": "getCategories",
+ "description": "Get available video categories",
+ "dataSchema": []
+ }
+ ]
+}
+```
+
+### 2. Get Playlists
+
+```bash
+postiz integrations:trigger youtube-123 getPlaylists
+```
+
+**Output:**
+```json
+{
+ "output": [
+ {
+ "id": "PLxxxxxx",
+ "title": "My Tutorials"
+ },
+ {
+ "id": "PLyyyyyy",
+ "title": "Product Demos"
+ }
+ ]
+}
+```
+
+### 3. Post to Specific Playlist
+
+```bash
+postiz posts:create \
+ -c "Video description" \
+ -p youtube \
+ --settings '{
+ "title": "My Video",
+ "type": "public",
+ "playlistId": "PLxxxxxx"
+ }' \
+ -i "youtube-123"
+```
+
+## Example: LinkedIn Companies
+
+### 1. Get LinkedIn Settings
+
+```bash
+postiz integrations:settings linkedin-123
+```
+
+**Output includes tools:**
+```json
+{
+ "tools": [
+ {
+ "methodName": "getCompanies",
+ "description": "Get companies you can post to",
+ "dataSchema": []
+ }
+ ]
+}
+```
+
+### 2. Get Companies
+
+```bash
+postiz integrations:trigger linkedin-123 getCompanies
+```
+
+**Output:**
+```json
+{
+ "output": [
+ {
+ "id": "company-123",
+ "name": "My Company"
+ },
+ {
+ "id": "company-456",
+ "name": "Other Company"
+ }
+ ]
+}
+```
+
+### 3. Post as Company
+
+```bash
+postiz posts:create \
+ -c "Company announcement" \
+ -p linkedin \
+ --settings '{
+ "companyId": "company-123"
+ }' \
+ -i "linkedin-123"
+```
+
+## Understanding Tools
+
+### Tool Structure
+
+```json
+{
+ "methodName": "getFlairs",
+ "description": "Get available flairs for a subreddit",
+ "dataSchema": [
+ {
+ "key": "subreddit",
+ "description": "The subreddit name",
+ "type": "string"
+ }
+ ]
+}
+```
+
+- **methodName** - Use this in `integrations:trigger`
+- **description** - What the tool does
+- **dataSchema** - Required input parameters
+
+### Calling Tools
+
+```bash
+# No parameters
+postiz integrations:trigger <integration-id> <methodName>
+
+# With parameters
+postiz integrations:trigger <integration-id> <methodName> -d '{"key":"value"}'
+```
+
+## Common Tool Methods
+
+### Reddit
+- `getFlairs` - Get flairs for a subreddit
+- `searchSubreddits` - Search for subreddits
+- `getSubreddits` - Get subscribed subreddits
+
+### YouTube
+- `getPlaylists` - Get your playlists
+- `getCategories` - Get video categories
+- `getChannels` - Get your channels
+
+### LinkedIn
+- `getCompanies` - Get companies you manage
+- `getOrganizations` - Get organizations
+
+### Twitter/X
+- `getListsowned` - Get your Twitter lists
+- `getCommunities` - Get communities you're in
+
+### Pinterest
+- `getBoards` - Get your Pinterest boards
+- `getBoardSections` - Get sections in a board
+
+## AI Agent Workflow
+
+For AI agents, this enables dynamic discovery and usage:
+
+```javascript
+// 1. Get settings and tools
+const settings = JSON.parse(
+ execSync(`postiz integrations:settings ${integrationId}`)
+);
+
+// 2. Check if tools are needed
+const tools = settings.output.tools || [];
+
+// 3. Call tools to get required data
+for (const tool of tools) {
+ if (needsThisTool(tool)) {
+ const data = buildDataForTool(tool.dataSchema);
+ const result = JSON.parse(
+ execSync(
+ `postiz integrations:trigger ${integrationId} ${tool.methodName} -d '${JSON.stringify(data)}'`
+ )
+ );
+
+ // Use result.output in your settings
+ updateSettings(result.output);
+ }
+}
+
+// 4. Create post with complete settings
+execSync(`postiz posts:create -c "${content}" --settings '${JSON.stringify(settings)}' -i "${integrationId}"`);
+```
+
+## Error Handling
+
+### Tool Not Found
+
+```bash
+postiz integrations:trigger reddit-123 invalidMethod
+# ❌ Failed to trigger tool: Tool not found
+```
+
+### Missing Required Data
+
+```bash
+postiz integrations:trigger reddit-123 getFlairs
+# ❌ Missing required parameter: subreddit
+```
+
+### Integration Not Found
+
+```bash
+postiz integrations:trigger invalid-id getFlairs
+# ❌ Failed to trigger tool: Integration not found
+```
+
+## Tips
+
+1. **Always check tools first** - Run `integrations:settings` to see available tools
+2. **Read dataSchema** - Know what parameters each tool needs
+3. **Parse JSON output** - Use `jq` or similar to extract data
+4. **Cache results** - Tool results don't change often
+5. **For AI agents** - Automate the entire workflow
+
+## Complete Example Script
+
+```bash
+#!/bin/bash
+export POSTIZ_API_KEY=your_key
+INTEGRATION_ID="reddit-abc123"
+
+# 1. Get settings
+echo "πŸ“‹ Getting settings..."
+SETTINGS=$(postiz integrations:settings $INTEGRATION_ID)
+echo $SETTINGS | jq '.output.tools'
+
+# 2. Get flairs
+echo ""
+echo "🏷️ Getting flairs..."
+FLAIRS=$(postiz integrations:trigger $INTEGRATION_ID getFlairs -d '{"subreddit":"programming"}')
+FLAIR_ID=$(echo $FLAIRS | jq -r '.output[0].id')
+FLAIR_NAME=$(echo $FLAIRS | jq -r '.output[0].name')
+
+echo "Selected flair: $FLAIR_NAME ($FLAIR_ID)"
+
+# 3. Create post
+echo ""
+echo "πŸ“ Creating post..."
+postiz posts:create \
+ -c "My post content" \
+ -p reddit \
+ --settings "{
+ \"subreddit\": [{
+ \"value\": {
+ \"subreddit\": \"programming\",
+ \"title\": \"My Post Title\",
+ \"type\": \"text\",
+ \"url\": \"\",
+ \"is_flair_required\": true,
+ \"flair\": {
+ \"id\": \"$FLAIR_ID\",
+ \"name\": \"$FLAIR_NAME\"
+ }
+ }
+ }]
+ }" \
+ -i "$INTEGRATION_ID"
+
+echo "βœ… Done!"
+```
+
+## Summary
+
+βœ… **Discover available tools** with `integrations:settings`
+βœ… **Call tools** to fetch required data with `integrations:trigger`
+βœ… **Use tool results** in post settings
+βœ… **Complete workflow** from discovery to posting
+βœ… **Perfect for AI agents** - fully automated
+βœ… **No guesswork** - know exactly what data you need
+
+**The CLI now supports the complete integration tools workflow!** πŸŽ‰
diff --git a/apps/cli/src/api.ts b/apps/cli/src/api.ts
index 96ec93ed8..0daa21c64 100644
--- a/apps/cli/src/api.ts
+++ b/apps/cli/src/api.ts
@@ -148,4 +148,15 @@ export class PostizAPI {
method: 'GET',
});
}
+
+ async triggerIntegrationTool(
+ integrationId: string,
+ methodName: string,
+ data: Record<string, string>
+ ) {
+ return this.request(`/public/v1/integration-trigger/${integrationId}`, {
+ method: 'POST',
+ body: JSON.stringify({ methodName, data }),
+ });
+ }
}
diff --git a/apps/cli/src/commands/integrations.ts b/apps/cli/src/commands/integrations.ts
index ced8f98e0..60cdc2033 100644
--- a/apps/cli/src/commands/integrations.ts
+++ b/apps/cli/src/commands/integrations.ts
@@ -35,3 +35,39 @@ export async function getIntegrationSettings(args: any) {
process.exit(1);
}
}
+
+export async function triggerIntegrationTool(args: any) {
+ const config = getConfig();
+ const api = new PostizAPI(config);
+
+ if (!args.id) {
+ console.error('❌ Integration ID is required');
+ process.exit(1);
+ }
+
+ if (!args.method) {
+ console.error('❌ Method name is required');
+ process.exit(1);
+ }
+
+ // Parse data from JSON string or use empty object
+ let data: Record<string, string> = {};
+ if (args.data) {
+ try {
+ data = JSON.parse(args.data);
+ } catch (error: any) {
+ console.error('❌ Failed to parse data JSON:', error.message);
+ process.exit(1);
+ }
+ }
+
+ try {
+ const result = await api.triggerIntegrationTool(args.id, args.method, data);
+ console.log(`πŸ”§ Tool result for ${args.method}:`);
+ console.log(JSON.stringify(result, null, 2));
+ return result;
+ } catch (error: any) {
+ console.error('❌ Failed to trigger tool:', error.message);
+ process.exit(1);
+ }
+}
diff --git a/apps/cli/src/index.ts b/apps/cli/src/index.ts
index 14c5d037d..3b410b9c6 100644
--- a/apps/cli/src/index.ts
+++ b/apps/cli/src/index.ts
@@ -1,7 +1,7 @@
import yargs from 'yargs';
import { hideBin } from 'yargs/helpers';
import { createPost, listPosts, deletePost } from './commands/posts';
-import { listIntegrations, getIntegrationSettings } from './commands/integrations';
+import { listIntegrations, getIntegrationSettings, triggerIntegrationTool } from './commands/integrations';
import { uploadFile } from './commands/upload';
import type { Argv } from 'yargs';
@@ -174,6 +174,39 @@ yargs(hideBin(process.argv))
},
getIntegrationSettings as any
)
+ .command(
+ 'integrations:trigger <id> <method>',
+ 'Trigger an integration tool to fetch additional data',
+ (yargs: Argv) => {
+ return yargs
+ .positional('id', {
+ describe: 'Integration ID',
+ type: 'string',
+ })
+ .positional('method', {
+ describe: 'Method name from the integration tools',
+ type: 'string',
+ })
+ .option('data', {
+ alias: 'd',
+ describe: 'Data to pass to the tool as JSON string',
+ type: 'string',
+ })
+ .example(
+ '$0 integrations:trigger reddit-123 getSubreddits',
+ 'Get list of subreddits'
+ )
+ .example(
+ '$0 integrations:trigger reddit-123 searchSubreddits -d \'{"query":"programming"}\'',
+ 'Search for subreddits'
+ )
+ .example(
+ '$0 integrations:trigger youtube-123 getPlaylists',
+ 'Get YouTube playlists'
+ );
+ },
+ triggerIntegrationTool as any
+ )
.command(
'upload <file>',
'Upload a file',