# Code Examples


Most users interact with Social Neuron through MCP clients like Claude Code or Claude Desktop, which handle the protocol automatically. These examples show the raw HTTP calls for custom integrations.

All tools are called via `POST /mcp` at `mcp.socialneuron.com` using JSON-RPC 2.0 with Bearer token authentication.

:::tip
Generate your API key at [socialneuron.com/settings/developer](https://socialneuron.com/settings/developer). Keys start with `snk_live_` and are tied to your plan's scopes.
:::

## cURL

### Generate Content

```bash
curl -X POST https://mcp.socialneuron.com/mcp \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer snk_live_your_api_key" \
  -d '{
    "jsonrpc": "2.0",
    "id": 1,
    "method": "tools/call",
    "params": {
      "name": "generate_content",
      "arguments": {
        "prompt": "Write a LinkedIn post about the benefits of AI in marketing",
        "platform": "linkedin",
        "tone": "professional"
      }
    }
  }'
```

**Response:**

```json
{
  "jsonrpc": "2.0",
  "id": 1,
  "result": {
    "content": [
      {
        "type": "text",
        "text": "{\"content\":\"The marketing teams winning today aren't working harder -- they're working smarter with AI.\\n\\nHere's what I've seen change in the last 12 months:\\n\\n1. Content creation time dropped by 60%\\n2. Engagement rates up 2.3x with personalized messaging\\n3. A/B testing cycles shortened from weeks to hours\\n\\nThe shift isn't about replacing creativity. It's about removing the bottlenecks that keep good ideas from reaching the right audience.\\n\\n#AIMarketing #ContentStrategy #MarTech\",\"platform\":\"linkedin\",\"creditsUsed\":2}"
      }
    ]
  }
}
```

### Schedule a Post

```bash
curl -X POST https://mcp.socialneuron.com/mcp \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer snk_live_your_api_key" \
  -d '{
    "jsonrpc": "2.0",
    "id": 2,
    "method": "tools/call",
    "params": {
      "name": "schedule_post",
      "arguments": {
        "platforms": ["instagram", "tiktok"],
        "caption": "Behind the scenes of our new product launch",
        "mediaUrl": "https://yourstorage.com/video.mp4",
        "scheduledFor": "2026-04-15T14:00:00Z"
      }
    }
  }'
```

**Response:**

```json
{
  "jsonrpc": "2.0",
  "id": 2,
  "result": {
    "content": [
      {
        "type": "text",
        "text": "{\"postIds\":[\"post_8f3a2b1c\",\"post_9d4e5f6a\"],\"scheduledFor\":\"2026-04-15T14:00:00Z\",\"platforms\":[\"instagram\",\"tiktok\"],\"status\":\"scheduled\"}"
      }
    ]
  }
}
```

### Check Credit Balance

```bash
curl -X POST https://mcp.socialneuron.com/mcp \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer snk_live_your_api_key" \
  -d '{
    "jsonrpc": "2.0",
    "id": 3,
    "method": "tools/call",
    "params": {
      "name": "get_credit_balance",
      "arguments": {}
    }
  }'
```

**Response:**

```json
{
  "jsonrpc": "2.0",
  "id": 3,
  "result": {
    "content": [
      {
        "type": "text",
        "text": "{\"creditsRemaining\":1420,\"monthlyAllocation\":2000,\"spendingCap\":5000,\"plan\":\"pro\",\"resetsAt\":\"2026-05-01T00:00:00Z\"}"
      }
    ]
  }
}
```

### Fetch Analytics

```bash
curl -X POST https://mcp.socialneuron.com/mcp \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer snk_live_your_api_key" \
  -d '{
    "jsonrpc": "2.0",
    "id": 4,
    "method": "tools/call",
    "params": {
      "name": "fetch_analytics",
      "arguments": {
        "platform": "instagram",
        "timeframe": "7d"
      }
    }
  }'
```

**Response:**

```json
{
  "jsonrpc": "2.0",
  "id": 4,
  "result": {
    "content": [
      {
        "type": "text",
        "text": "{\"platform\":\"instagram\",\"timeframe\":\"7d\",\"summary\":{\"totalPosts\":12,\"totalImpressions\":48200,\"totalEngagements\":3150,\"engagementRate\":6.53,\"followerChange\":340},\"topPost\":{\"caption\":\"Behind the scenes of our new product launch\",\"impressions\":12400,\"engagements\":890}}"
      }
    ]
  }
}
```

---

## JavaScript (Node.js)

All examples use the built-in `fetch()` API -- no external dependencies required.

### Generate Content

```javascript
const response = await fetch("https://mcp.socialneuron.com/mcp", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    Authorization: "Bearer snk_live_your_api_key",
  },
  body: JSON.stringify({
    jsonrpc: "2.0",
    id: 1,
    method: "tools/call",
    params: {
      name: "generate_content",
      arguments: {
        prompt: "Write a Twitter thread about remote work productivity tips",
        platform: "twitter",
        tone: "conversational",
      },
    },
  }),
});

const data = await response.json();
const result = JSON.parse(data.result.content[0].text);
console.log(result.content);
```

**Response:**

```json
{
  "jsonrpc": "2.0",
  "id": 1,
  "result": {
    "content": [
      {
        "type": "text",
        "text": "{\"content\":\"Remote work changed how we think about productivity. Here are 5 things that actually moved the needle for our team:\\n\\n1/ Block your calendar ruthlessly. If it's not on the calendar, it doesn't exist.\\n\\n2/ Async by default. Not every question needs a meeting.\\n\\n3/ Document decisions, not just discussions.\\n\\n4/ Take real breaks. Walking away from the screen is not slacking.\\n\\n5/ End each day with a 2-minute brain dump. Tomorrow-you will thank you.\",\"platform\":\"twitter\",\"creditsUsed\":2}"
      }
    ]
  }
}
```

### Schedule a Post

```javascript
const response = await fetch("https://mcp.socialneuron.com/mcp", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    Authorization: "Bearer snk_live_your_api_key",
  },
  body: JSON.stringify({
    jsonrpc: "2.0",
    id: 2,
    method: "tools/call",
    params: {
      name: "schedule_post",
      arguments: {
        platforms: ["linkedin", "twitter"],
        caption: "Excited to announce our Series A funding!",
        mediaUrl: "https://yourstorage.com/announcement.png",
        scheduledFor: "2026-04-20T09:00:00Z",
      },
    },
  }),
});

const data = await response.json();
const result = JSON.parse(data.result.content[0].text);
console.log(`Scheduled ${result.postIds.length} posts`);
```

**Response:**

```json
{
  "jsonrpc": "2.0",
  "id": 2,
  "result": {
    "content": [
      {
        "type": "text",
        "text": "{\"postIds\":[\"post_a1b2c3d4\",\"post_e5f6g7h8\"],\"scheduledFor\":\"2026-04-20T09:00:00Z\",\"platforms\":[\"linkedin\",\"twitter\"],\"status\":\"scheduled\"}"
      }
    ]
  }
}
```

### Check Credit Balance

```javascript
const response = await fetch("https://mcp.socialneuron.com/mcp", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    Authorization: "Bearer snk_live_your_api_key",
  },
  body: JSON.stringify({
    jsonrpc: "2.0",
    id: 3,
    method: "tools/call",
    params: {
      name: "get_credit_balance",
      arguments: {},
    },
  }),
});

const data = await response.json();
const result = JSON.parse(data.result.content[0].text);
console.log(`${result.creditsRemaining} / ${result.monthlyAllocation} credits remaining`);
```

### Fetch Analytics

```javascript
const response = await fetch("https://mcp.socialneuron.com/mcp", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    Authorization: "Bearer snk_live_your_api_key",
  },
  body: JSON.stringify({
    jsonrpc: "2.0",
    id: 4,
    method: "tools/call",
    params: {
      name: "fetch_analytics",
      arguments: {
        platform: "tiktok",
        timeframe: "30d",
      },
    },
  }),
});

const data = await response.json();
const result = JSON.parse(data.result.content[0].text);
console.log(`Engagement rate: ${result.summary.engagementRate}%`);
```

**Response:**

```json
{
  "jsonrpc": "2.0",
  "id": 4,
  "result": {
    "content": [
      {
        "type": "text",
        "text": "{\"platform\":\"tiktok\",\"timeframe\":\"30d\",\"summary\":{\"totalPosts\":28,\"totalImpressions\":215000,\"totalEngagements\":18400,\"engagementRate\":8.56,\"followerChange\":1280},\"topPost\":{\"caption\":\"Day in the life running a SaaS startup\",\"impressions\":42000,\"engagements\":5100}}"
      }
    ]
  }
}
```

---

## Python

All examples use the `requests` library. Install it with `pip install requests`.

### Generate Content

```python
import requests
import json

response = requests.post(
    "https://mcp.socialneuron.com/mcp",
    headers={
        "Content-Type": "application/json",
        "Authorization": "Bearer snk_live_your_api_key",
    },
    json={
        "jsonrpc": "2.0",
        "id": 1,
        "method": "tools/call",
        "params": {
            "name": "generate_content",
            "arguments": {
                "prompt": "Write an Instagram caption for a coffee brand product photo",
                "platform": "instagram",
                "tone": "playful",
            },
        },
    },
)

data = response.json()
result = json.loads(data["result"]["content"][0]["text"])
print(result["content"])
```

**Response:**

```json
{
  "jsonrpc": "2.0",
  "id": 1,
  "result": {
    "content": [
      {
        "type": "text",
        "text": "{\"content\":\"Your morning called. It wants an upgrade.\\n\\nOur new single-origin blend from Colombia hits different -- smooth, bright, and just enough sweetness to make you forget you're awake at 6 AM.\\n\\nAvailable now. Your taste buds can thank us later.\\n\\n#CoffeeLovers #SingleOrigin #MorningRitual #NewBlend\",\"platform\":\"instagram\",\"creditsUsed\":2}"
      }
    ]
  }
}
```

### Schedule a Post

```python
import requests
import json

response = requests.post(
    "https://mcp.socialneuron.com/mcp",
    headers={
        "Content-Type": "application/json",
        "Authorization": "Bearer snk_live_your_api_key",
    },
    json={
        "jsonrpc": "2.0",
        "id": 2,
        "method": "tools/call",
        "params": {
            "name": "schedule_post",
            "arguments": {
                "platforms": ["instagram", "facebook"],
                "caption": "New collection dropping this Friday. Set your alarms.",
                "mediaUrl": "https://yourstorage.com/teaser.mp4",
                "scheduledFor": "2026-04-18T18:00:00Z",
            },
        },
    },
)

data = response.json()
result = json.loads(data["result"]["content"][0]["text"])
for post_id in result["postIds"]:
    print(f"Scheduled: {post_id}")
```

### Check Credit Balance

```python
import requests
import json

response = requests.post(
    "https://mcp.socialneuron.com/mcp",
    headers={
        "Content-Type": "application/json",
        "Authorization": "Bearer snk_live_your_api_key",
    },
    json={
        "jsonrpc": "2.0",
        "id": 3,
        "method": "tools/call",
        "params": {
            "name": "get_credit_balance",
            "arguments": {},
        },
    },
)

data = response.json()
result = json.loads(data["result"]["content"][0]["text"])
print(f"{result['creditsRemaining']} credits remaining (resets {result['resetsAt']})")
```

### Fetch Analytics

```python
import requests
import json

response = requests.post(
    "https://mcp.socialneuron.com/mcp",
    headers={
        "Content-Type": "application/json",
        "Authorization": "Bearer snk_live_your_api_key",
    },
    json={
        "jsonrpc": "2.0",
        "id": 4,
        "method": "tools/call",
        "params": {
            "name": "fetch_analytics",
            "arguments": {
                "platform": "youtube",
                "timeframe": "30d",
            },
        },
    },
)

data = response.json()
result = json.loads(data["result"]["content"][0]["text"])
summary = result["summary"]
print(f"Posts: {summary['totalPosts']}")
print(f"Impressions: {summary['totalImpressions']:,}")
print(f"Engagement rate: {summary['engagementRate']}%")
```

**Response:**

```json
{
  "jsonrpc": "2.0",
  "id": 4,
  "result": {
    "content": [
      {
        "type": "text",
        "text": "{\"platform\":\"youtube\",\"timeframe\":\"30d\",\"summary\":{\"totalPosts\":8,\"totalImpressions\":94500,\"totalEngagements\":7200,\"engagementRate\":7.62,\"followerChange\":520},\"topPost\":{\"caption\":\"How we grew from 0 to 10K subscribers in 90 days\",\"impressions\":31000,\"engagements\":2800}}"
      }
    ]
  }
}
```

---

## Error Handling

All error responses follow the JSON-RPC 2.0 error format:

```json
{
  "jsonrpc": "2.0",
  "id": 1,
  "error": {
    "code": -32600,
    "message": "INSUFFICIENT_CREDITS",
    "data": {
      "detail": "This operation requires 5 credits but you have 2 remaining."
    }
  }
}
```

Common error codes:

| Code | JSON-RPC Code | Meaning |
|------|--------------|---------|
| `UNAUTHORIZED` | -32001 | Missing or invalid API key |
| `FORBIDDEN` | -32002 | Your plan does not include this scope |
| `RATE_LIMITED` | -32003 | Too many requests -- check `X-RateLimit-Reset` header |
| `INSUFFICIENT_CREDITS` | -32004 | Not enough credits for this operation |
| `VALIDATION_ERROR` | -32602 | Missing or invalid parameters |

:::warning
Always check for the `error` field in the JSON-RPC response before using the `result`. Network errors, expired keys, and insufficient credits can all cause failures.
:::

---

Ready to try this? [Sign up free](https://socialneuron.com) and get 50 free credits to start.
