mcp-confluence 1.0.0

MCP server for Confluence integration - create, update, search, and manage Confluence pages
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
use serde_json::Value;

use crate::client::ConfluenceClient;
use crate::formatters::format_page_detailed;
use crate::mcp::{CallToolResult, ToolDefinition};
use crate::types::{
    AnyPage, ConfluencePage, ConfluencePageV1, CreatePageResponse, PageListResponseV1,
    SearchResult, SpaceListResponse,
};

use super::schema;

pub fn definitions() -> Vec<ToolDefinition> {
    vec![
        ToolDefinition {
            name: "get_page".to_string(),
            description: "Fetch a Confluence page by its ID or title".to_string(),
            input_schema: schema(&[
                ("pageId", "string", false, "The page ID (e.g., '123456')"),
                ("spaceKey", "string", false, "The space key (required if using title)"),
                ("title", "string", false, "The page title (requires spaceKey)"),
                ("includeBody", "boolean", false, "Whether to include the page body content (default: true)"),
            ]),
        },
        ToolDefinition {
            name: "get_page_full".to_string(),
            description: "Fetch complete Confluence page content in storage format (for automation, analysis, or export). Returns raw storage format without markdown conversion.".to_string(),
            input_schema: schema(&[
                ("pageId", "string", false, "The page ID (e.g., '123456')"),
                ("spaceKey", "string", false, "The space key (required if using title)"),
                ("title", "string", false, "The page title (requires spaceKey)"),
            ]),
        },
        ToolDefinition {
            name: "create_page".to_string(),
            description: "Create a new Confluence page".to_string(),
            input_schema: schema(&[
                ("spaceKey", "string", true, "The space key where the page will be created"),
                ("title", "string", true, "The title of the page"),
                ("content", "string", true, "The page content in HTML or storage format"),
                ("parentPageId", "string", false, "The ID of the parent page (for nested pages)"),
            ]),
        },
        ToolDefinition {
            name: "update_page".to_string(),
            description: "Update an existing Confluence page".to_string(),
            input_schema: schema(&[
                ("pageId", "string", true, "The ID of the page to update"),
                ("title", "string", false, "New title for the page (optional)"),
                ("content", "string", true, "The new page content in HTML or storage format"),
                ("versionComment", "string", false, "A comment describing this update"),
            ]),
        },
        ToolDefinition {
            name: "delete_page".to_string(),
            description: "Delete a Confluence page".to_string(),
            input_schema: schema(&[
                ("pageId", "string", true, "The ID of the page to delete"),
            ]),
        },
    ]
}

/// Fetch a page by ID or title.
pub async fn get_page(client: &ConfluenceClient, args: &Value) -> CallToolResult {
    let page_id = args.get("pageId").and_then(|v| v.as_str());
    let space_key = args.get("spaceKey").and_then(|v| v.as_str());
    let title = args.get("title").and_then(|v| v.as_str());
    let include_body = args.get("includeBody").and_then(|v| v.as_bool()).unwrap_or(true);

    if page_id.is_none() && (space_key.is_none() || title.is_none()) {
        return CallToolResult::text(
            "Error: Please provide either pageId, or both spaceKey and title.",
        );
    }

    let cfg = client.config();
    let result: Result<AnyPage, String> = if cfg.is_cloud {
        fetch_page_cloud(client, page_id, space_key, title, include_body).await
    } else {
        fetch_page_server(client, page_id, space_key, title, include_body).await
    };

    match result {
        Ok(page) => CallToolResult::text(format_page_detailed(
            &page,
            &cfg.host,
            cfg.is_cloud,
            cfg.max_content_length,
        )),
        Err(e) => CallToolResult::text(format!("Error fetching page: {e}")),
    }
}

/// Get page in raw storage format.
pub async fn get_page_full(client: &ConfluenceClient, args: &Value) -> CallToolResult {
    let page_id = args.get("pageId").and_then(|v| v.as_str());
    let space_key = args.get("spaceKey").and_then(|v| v.as_str());
    let title = args.get("title").and_then(|v| v.as_str());

    if page_id.is_none() && (space_key.is_none() || title.is_none()) {
        return CallToolResult::text(
            "Error: Please provide either pageId, or both spaceKey and title.",
        );
    }

    let cfg = client.config();
    let result: Result<AnyPage, String> = if cfg.is_cloud {
        fetch_page_cloud(client, page_id, space_key, title, true).await
    } else {
        fetch_page_server(client, page_id, space_key, title, true).await
    };

    match result {
        Ok(page) => {
            let storage = page.storage_value().to_string();
            let size = storage.len();
            let url = page.webui_link().map_or_else(
                || format!("{}/pages/{}", cfg.host, page.id()),
                |w| {
                    if w.starts_with('/') {
                        let prefix = if cfg.is_cloud { "/wiki" } else { "" };
                        format!("{}{prefix}{w}", cfg.host)
                    } else {
                        w.to_string()
                    }
                },
            );

            CallToolResult::text(format!(
                "**Page:** {} (ID: {})\n**Version:** {}\n**Size:** {} bytes\n**URL:** {}\n\n---\n\n**Raw Storage Format:**\n\n```xml\n{}\n```",
                page.title(),
                page.id(),
                page.version_number(),
                size,
                url,
                storage,
            ))
        }
        Err(e) => CallToolResult::text(format!("Error fetching page: {e}")),
    }
}

/// Create a new page.
pub async fn create_page(client: &ConfluenceClient, args: &Value) -> CallToolResult {
    let space_key = match args.get("spaceKey").and_then(|v| v.as_str()) {
        Some(k) => k,
        None => return CallToolResult::text("Error: spaceKey is required."),
    };
    let title = match args.get("title").and_then(|v| v.as_str()) {
        Some(t) => t,
        None => return CallToolResult::text("Error: title is required."),
    };
    let content = match args.get("content").and_then(|v| v.as_str()) {
        Some(c) => c,
        None => return CallToolResult::text("Error: content is required."),
    };
    let parent_page_id = args.get("parentPageId").and_then(|v| v.as_str());

    let cfg = client.config();

    let result: Result<CreatePageResponse, String> = if cfg.is_cloud {
        // Get space ID from key
        let spaces: SpaceListResponse = match client.get(&format!("/spaces?keys={space_key}")).await
        {
            Ok(s) => s,
            Err(e) => return CallToolResult::text(format!("Error creating page: {e}")),
        };
        if spaces.results.is_empty() {
            return CallToolResult::text(format!("Space with key \"{space_key}\" not found."));
        }
        let space_id = &spaces.results[0].id;

        let mut body = serde_json::json!({
            "spaceId": space_id,
            "status": "current",
            "title": title,
            "body": {
                "representation": "storage",
                "value": content,
            }
        });
        if let Some(pid) = parent_page_id {
            body["parentId"] = Value::String(pid.to_string());
        }

        client.post("/pages", &body).await
    } else {
        let mut body = serde_json::json!({
            "type": "page",
            "title": title,
            "space": { "key": space_key },
            "body": {
                "storage": {
                    "value": content,
                    "representation": "storage"
                }
            }
        });
        if let Some(pid) = parent_page_id {
            body["ancestors"] = serde_json::json!([{ "id": pid }]);
        }

        client.post("/content", &body).await
    };

    match result {
        Ok(resp) => {
            let web_url = resp.links.as_ref().and_then(|l| l.webui.as_ref()).map_or_else(
                || format!("{}/wiki/spaces/{space_key}/pages/{}", cfg.host, resp.id),
                |w| {
                    if w.starts_with('/') {
                        let prefix = if cfg.is_cloud { "/wiki" } else { "" };
                        format!("{}{prefix}{w}", cfg.host)
                    } else {
                        w.to_string()
                    }
                },
            );
            CallToolResult::text(format!(
                "✅ Page created successfully!\n\n**Title**: {}\n**ID**: {}\n**URL**: {}",
                resp.title, resp.id, web_url
            ))
        }
        Err(e) => CallToolResult::text(format!("Error creating page: {e}")),
    }
}

/// Update an existing page.
pub async fn update_page(client: &ConfluenceClient, args: &Value) -> CallToolResult {
    let page_id = match args.get("pageId").and_then(|v| v.as_str()) {
        Some(id) => id,
        None => return CallToolResult::text("Error: pageId is required."),
    };
    let title = args.get("title").and_then(|v| v.as_str());
    let content = match args.get("content").and_then(|v| v.as_str()) {
        Some(c) => c,
        None => return CallToolResult::text("Error: content is required."),
    };
    let version_comment = args.get("versionComment").and_then(|v| v.as_str());

    let cfg = client.config();

    let result: Result<(), String> = async {
        if cfg.is_cloud {
            let current: ConfluencePage = client.get(&format!("/pages/{page_id}")).await?;
            let current_version = current.version.as_ref().map_or(1, |v| v.number);
            let current_title = current.title.clone();

            let body = serde_json::json!({
                "id": page_id,
                "status": "current",
                "title": title.unwrap_or(&current_title),
                "body": {
                    "representation": "storage",
                    "value": content,
                },
                "version": {
                    "number": current_version + 1,
                    "message": version_comment,
                }
            });

            client.put::<Value>(&format!("/pages/{page_id}"), &body).await?;
            Ok(())
        } else {
            let current: ConfluencePageV1 = client
                .get(&format!("/content/{page_id}?expand=version"))
                .await?;
            let current_version = current.version.as_ref().map_or(1, |v| v.number);
            let current_title = current.title.clone();

            let body = serde_json::json!({
                "type": "page",
                "title": title.unwrap_or(&current_title),
                "body": {
                    "storage": {
                        "value": content,
                        "representation": "storage"
                    }
                },
                "version": {
                    "number": current_version + 1,
                    "message": version_comment,
                }
            });

            client.put::<Value>(&format!("/content/{page_id}"), &body).await?;
            Ok(())
        }
    }
    .await;

    match result {
        Ok(()) => CallToolResult::text(format!(
            "✅ Page updated successfully!\n\n**ID**: {page_id}"
        )),
        Err(e) => CallToolResult::text(format!("Error updating page: {e}")),
    }
}

/// Delete a page.
pub async fn delete_page(client: &ConfluenceClient, args: &Value) -> CallToolResult {
    let page_id = match args.get("pageId").and_then(|v| v.as_str()) {
        Some(id) => id,
        None => return CallToolResult::text("Error: pageId is required."),
    };

    let endpoint = if client.config().is_cloud {
        format!("/pages/{page_id}")
    } else {
        format!("/content/{page_id}")
    };

    match client.delete(&endpoint).await {
        Ok(()) => CallToolResult::text(format!("✅ Page {page_id} deleted successfully.")),
        Err(e) => CallToolResult::text(format!("Error deleting page: {e}")),
    }
}

// ── helpers ──

async fn fetch_page_cloud(
    client: &ConfluenceClient,
    page_id: Option<&str>,
    space_key: Option<&str>,
    title: Option<&str>,
    include_body: bool,
) -> Result<AnyPage, String> {
    if let Some(pid) = page_id {
        let body_format = if include_body { "&body-format=storage" } else { "" };
        let page: ConfluencePage = client.get(&format!("/pages/{pid}?{body_format}")).await?;
        Ok(AnyPage::V2(page))
    } else {
        let cql = format!(
            "space=\"{}\" AND title=\"{}\"",
            space_key.unwrap(),
            title.unwrap()
        );
        let search: SearchResult = client
            .get_v1(&format!(
                "/search?cql={}&limit=1",
                urlencoding(&cql)
            ))
            .await?;

        if search.results.is_empty() || search.results[0].content.is_none() {
            return Err(format!(
                "Page \"{}\" not found in space {}.",
                title.unwrap(),
                space_key.unwrap()
            ));
        }
        let found_id = &search.results[0].content.as_ref().unwrap().id;
        let body_format = if include_body { "&body-format=storage" } else { "" };
        let page: ConfluencePage =
            client.get(&format!("/pages/{found_id}?{body_format}")).await?;
        Ok(AnyPage::V2(page))
    }
}

async fn fetch_page_server(
    client: &ConfluenceClient,
    page_id: Option<&str>,
    space_key: Option<&str>,
    title: Option<&str>,
    include_body: bool,
) -> Result<AnyPage, String> {
    let expand = if include_body {
        "body.storage,version,ancestors,space"
    } else {
        "version,ancestors,space"
    };

    if let Some(pid) = page_id {
        let page: ConfluencePageV1 =
            client.get(&format!("/content/{pid}?expand={expand}")).await?;
        Ok(AnyPage::V1(page))
    } else {
        let result: PageListResponseV1 = client
            .get(&format!(
                "/content?spaceKey={}&title={}&expand={expand}",
                space_key.unwrap(),
                urlencoding(title.unwrap())
            ))
            .await?;

        if result.results.is_empty() {
            return Err(format!(
                "Page \"{}\" not found in space {}.",
                title.unwrap(),
                space_key.unwrap()
            ));
        }
        Ok(AnyPage::V1(result.results.into_iter().next().unwrap()))
    }
}

fn urlencoding(s: &str) -> String {
    let mut out = String::new();
    for b in s.bytes() {
        match b {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
                out.push(b as char)
            }
            _ => {
                out.push('%');
                out.push_str(&format!("{b:02X}"));
            }
        }
    }
    out
}