micropub 0.4.1

Ultra-compliant Micropub CLI for creating, updating, and managing IndieWeb posts
Documentation
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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
// ABOUTME: Model Context Protocol (MCP) server implementation
// ABOUTME: Provides tools for AI assistants to post and manage micropub content

use anyhow::Result;
use base64::{engine::general_purpose, Engine as _};
use chrono::{DateTime, Utc};
use rmcp::handler::server::router::prompt::PromptRouter;
use rmcp::handler::server::router::tool::ToolRouter;
use rmcp::handler::server::wrapper::Parameters;
use rmcp::model::{
    CallToolResult, Content, ErrorCode, GetPromptRequestParam, GetPromptResult, Implementation,
    ListPromptsResult, PaginatedRequestParam, PromptMessage, PromptMessageRole, ProtocolVersion,
    ServerCapabilities, ServerInfo,
};
use rmcp::prompt;
use rmcp::prompt_handler;
use rmcp::prompt_router;
use rmcp::service::RequestContext;
use rmcp::tool;
use rmcp::tool_handler;
use rmcp::tool_router;
use rmcp::transport::stdio;
use rmcp::ErrorData as McpError;
use rmcp::{schemars, RoleServer, ServerHandler, ServiceExt};

use crate::config::Config;
use crate::draft::Draft;
use crate::draft_push::validate_draft_id;
use crate::publish;

/// Parameters for publish_post tool
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct PublishPostArgs {
    /// The content of the post
    pub content: String,
    /// Optional title for the post
    #[serde(skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
    /// Optional comma-separated categories
    #[serde(skip_serializing_if = "Option::is_none")]
    pub categories: Option<String>,
}

/// Parameters for create_draft tool
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct CreateDraftArgs {
    /// The content of the draft
    pub content: String,
    /// Optional title for the draft
    #[serde(skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
}

/// Parameters for publish_backdate tool
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct PublishBackdateArgs {
    /// The draft ID to publish (alphanumeric, hyphens, underscores only)
    #[schemars(regex(pattern = r"^[a-zA-Z0-9_-]+$"))]
    pub draft_id: String,
    /// ISO 8601 formatted date (e.g., 2024-01-15T10:30:00Z)
    pub date: String,
}

/// Parameters for delete_post tool
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct DeletePostArgs {
    /// The URL of the post to delete
    #[schemars(url)]
    pub url: String,
}

/// Parameters for list_posts tool
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct ListPostsArgs {
    /// Number of posts to retrieve (default: 10)
    #[serde(default = "default_limit")]
    pub limit: usize,
    /// Offset for pagination (default: 0)
    #[serde(default)]
    pub offset: usize,
}

/// Parameters for view_draft tool
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct ViewDraftArgs {
    /// The draft ID to view
    #[schemars(regex(pattern = r"^[a-zA-Z0-9_-]+$"))]
    pub draft_id: String,
}

/// Parameters for list_media tool
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct ListMediaArgs {
    /// Number of media items to retrieve (default: 20)
    #[serde(default = "default_media_limit")]
    pub limit: usize,
    /// Offset for pagination (default: 0)
    #[serde(default)]
    pub offset: usize,
}

/// Parameters for upload_media tool
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct UploadMediaArgs {
    /// Path to local file (e.g., ~/Pictures/photo.jpg)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub file_path: Option<String>,

    /// Base64-encoded file data (alternative to file_path)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub file_data: Option<String>,

    /// Filename (required when using file_data)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub filename: Option<String>,

    /// Optional alt text for accessibility
    #[serde(skip_serializing_if = "Option::is_none")]
    pub alt_text: Option<String>,
}

/// Parameters for push_draft tool
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct PushDraftArgs {
    /// The draft ID to push to the server as a server-side draft
    #[schemars(regex(pattern = r"^[a-zA-Z0-9_-]+$"))]
    pub draft_id: String,
    /// Optional ISO 8601 formatted date for backdating (e.g., 2024-01-15T10:30:00Z)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub backdate: Option<String>,
}

fn default_limit() -> usize {
    10
}

fn default_media_limit() -> usize {
    20
}

/// Parameters for quick-note prompt
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct QuickNotePromptArgs {
    /// The topic or subject you want to write about (1-200 characters)
    #[schemars(length(min = 1, max = 200))]
    pub topic: String,
}

/// Parameters for photo-post prompt
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct PhotoPostPromptArgs {
    /// What the photo is about or depicts (1-200 characters)
    #[schemars(length(min = 1, max = 200))]
    pub subject: String,
}

/// Parameters for article-draft prompt
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct ArticleDraftPromptArgs {
    /// The article topic or title (1-200 characters)
    #[schemars(length(min = 1, max = 200))]
    pub topic: String,
    /// Key points to cover (optional, max 500 characters)
    #[serde(skip_serializing_if = "Option::is_none")]
    #[schemars(length(max = 500))]
    pub key_points: Option<String>,
}

/// Parameters for backdate-memory prompt
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct BackdateMemoryPromptArgs {
    /// What event or memory to record (1-300 characters)
    #[schemars(length(min = 1, max = 300))]
    pub memory: String,
    /// When it happened (e.g., "last Tuesday", "2024-01-15") (1-100 characters)
    #[schemars(length(min = 1, max = 100))]
    pub when: String,
}

/// Parameters for categorized-post prompt
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct CategorizedPostPromptArgs {
    /// The post topic (1-200 characters)
    #[schemars(length(min = 1, max = 200))]
    pub topic: String,
    /// Categories for the post (comma-separated, 1-100 characters)
    #[schemars(length(min = 1, max = 100))]
    pub categories: String,
}

/// MCP server state
#[derive(Clone)]
pub struct MicropubMcp {
    tool_router: ToolRouter<MicropubMcp>,
    prompt_router: PromptRouter<MicropubMcp>,
}

impl MicropubMcp {
    /// Create a new MCP server instance
    pub fn new() -> Result<Self> {
        Ok(Self {
            tool_router: Self::tool_router(),
            prompt_router: Self::prompt_router(),
        })
    }
}

#[tool_router]
impl MicropubMcp {
    /// Create and publish a post immediately
    #[tool(
        description = "Create and publish a micropub post with optional title and categories. Automatically detects and uploads local image files (e.g., ![alt](~/photo.jpg) or <img src='/path/image.png'>) and replaces them with permanent URLs before publishing."
    )]
    async fn publish_post(
        &self,
        Parameters(args): Parameters<PublishPostArgs>,
    ) -> Result<CallToolResult, McpError> {
        // Validate content is not empty
        if args.content.trim().is_empty() {
            return Err(McpError::invalid_params(
                "Content cannot be empty".to_string(),
                None,
            ));
        }

        // Create a draft first
        let mut draft = Draft::new(uuid::Uuid::new_v4().to_string());
        draft.content = args.content;
        draft.metadata.name = args.title;

        // Parse categories as comma-separated
        if let Some(cats) = args.categories {
            draft.metadata.category = cats.split(',').map(|s| s.trim().to_string()).collect();
        }

        let draft_path = draft.save().map_err(|e| {
            McpError::new(
                ErrorCode::INTERNAL_ERROR,
                format!("Failed to save draft: {}", e),
                None,
            )
        })?;

        // Publish it
        let draft_path_str = draft_path.to_str().ok_or_else(|| {
            McpError::new(
                ErrorCode::INTERNAL_ERROR,
                "Draft path contains invalid UTF-8".to_string(),
                None,
            )
        })?;

        let uploads = publish::cmd_publish(draft_path_str, None)
            .await
            .map_err(|e| {
                McpError::new(
                    ErrorCode::INTERNAL_ERROR,
                    format!("Failed to publish: {}", e),
                    None,
                )
            })?;

        let mut message = String::from("Post published successfully!");

        if !uploads.is_empty() {
            message.push_str("\n\nUploaded media:");
            for (filename, url) in uploads {
                message.push_str(&format!("\n- {} -> {}", filename, url));
            }
        }

        Ok(CallToolResult::success(vec![Content::text(message)]))
    }

    /// Create a draft post without publishing
    #[tool(description = "Create a draft micropub post for later editing and publishing")]
    async fn create_draft(
        &self,
        Parameters(args): Parameters<CreateDraftArgs>,
    ) -> Result<CallToolResult, McpError> {
        // Validate content is not empty
        if args.content.trim().is_empty() {
            return Err(McpError::invalid_params(
                "Content cannot be empty".to_string(),
                None,
            ));
        }

        let mut draft = Draft::new(uuid::Uuid::new_v4().to_string());
        draft.content = args.content;
        draft.metadata.name = args.title;

        draft.save().map_err(|e| {
            McpError::new(
                ErrorCode::INTERNAL_ERROR,
                format!("Failed to create draft: {}", e),
                None,
            )
        })?;

        Ok(CallToolResult::success(vec![Content::text(format!(
            "Draft created with ID: {}",
            draft.id
        ))]))
    }

    /// List all draft posts
    #[tool(description = "List all draft micropub posts")]
    async fn list_drafts(&self) -> Result<CallToolResult, McpError> {
        let draft_ids = Draft::list_all().map_err(|e| {
            McpError::new(
                ErrorCode::INTERNAL_ERROR,
                format!("Failed to list drafts: {}", e),
                None,
            )
        })?;

        if draft_ids.is_empty() {
            return Ok(CallToolResult::success(vec![Content::text(
                "No drafts found.",
            )]));
        }

        let mut output = String::from("Drafts:\n");
        for id in draft_ids {
            if let Ok(draft) = Draft::load(&id) {
                let title = draft
                    .metadata
                    .name
                    .unwrap_or_else(|| "[untitled]".to_string());
                output.push_str(&format!("- {} ({})\n", title, id));
            }
        }

        Ok(CallToolResult::success(vec![Content::text(output)]))
    }

    /// Publish a draft with a backdated timestamp
    #[tool(description = "Publish a draft post with a specific past date (ISO 8601 format)")]
    async fn publish_backdate(
        &self,
        Parameters(args): Parameters<PublishBackdateArgs>,
    ) -> Result<CallToolResult, McpError> {
        // Validate draft_id format to prevent path traversal
        validate_draft_id(&args.draft_id)
            .map_err(|e| McpError::invalid_params(format!("Invalid draft ID: {}", e), None))?;

        // Parse the date
        let parsed_date = DateTime::parse_from_rfc3339(&args.date)
            .map_err(|e| {
                McpError::invalid_params(
                    format!(
                        "Invalid date format: {}. Use ISO 8601 like 2024-01-15T10:30:00Z",
                        e
                    ),
                    None,
                )
            })?
            .with_timezone(&Utc);

        // Load draft path
        let draft_path = crate::config::get_drafts_dir()
            .map_err(|e| {
                McpError::new(
                    ErrorCode::INTERNAL_ERROR,
                    format!("Failed to get drafts dir: {}", e),
                    None,
                )
            })?
            .join(format!("{}.md", args.draft_id));

        if !draft_path.exists() {
            return Err(McpError::invalid_params(
                format!("Draft not found: {}", args.draft_id),
                None,
            ));
        }

        // Publish with backdate
        let draft_path_str = draft_path.to_str().ok_or_else(|| {
            McpError::new(
                ErrorCode::INTERNAL_ERROR,
                "Draft path contains invalid UTF-8".to_string(),
                None,
            )
        })?;

        let uploads = publish::cmd_publish(draft_path_str, Some(parsed_date))
            .await
            .map_err(|e| {
                McpError::new(
                    ErrorCode::INTERNAL_ERROR,
                    format!("Failed to publish: {}", e),
                    None,
                )
            })?;

        let mut message = format!("Post published with backdated timestamp: {}", args.date);

        if !uploads.is_empty() {
            message.push_str("\n\nUploaded media:");
            for (filename, url) in uploads {
                message.push_str(&format!("\n- {} -> {}", filename, url));
            }
        }

        Ok(CallToolResult::success(vec![Content::text(message)]))
    }

    /// Delete a published post
    #[tool(description = "Delete a published micropub post by URL")]
    async fn delete_post(
        &self,
        Parameters(args): Parameters<DeletePostArgs>,
    ) -> Result<CallToolResult, McpError> {
        // Validate URL is not empty
        if args.url.is_empty() {
            return Err(McpError::invalid_params(
                "URL cannot be empty".to_string(),
                None,
            ));
        }

        crate::operations::cmd_delete(&args.url)
            .await
            .map_err(|e| {
                McpError::new(
                    ErrorCode::INTERNAL_ERROR,
                    format!("Failed to delete post: {}", e),
                    None,
                )
            })?;

        Ok(CallToolResult::success(vec![Content::text(format!(
            "Post deleted: {}",
            args.url
        ))]))
    }

    /// Get authentication status
    #[tool(description = "Check which micropub account is currently authenticated")]
    async fn whoami(&self) -> Result<CallToolResult, McpError> {
        let config = Config::load().map_err(|e| {
            McpError::new(
                ErrorCode::INTERNAL_ERROR,
                format!("Failed to load config: {}", e),
                None,
            )
        })?;

        let profile_name = &config.default_profile;
        if profile_name.is_empty() {
            return Ok(CallToolResult::success(vec![Content::text(
                "No profile configured. Run 'micropub auth <domain>' first.",
            )]));
        }

        let profile = config.get_profile(profile_name).ok_or_else(|| {
            McpError::new(
                ErrorCode::INTERNAL_ERROR,
                "Profile not found".to_string(),
                None,
            )
        })?;

        let output = format!(
            "Authenticated as:\n  Profile: {}\n  Domain: {}\n  Micropub: {}",
            profile_name,
            profile.domain,
            profile
                .micropub_endpoint
                .as_deref()
                .unwrap_or("(not configured)")
        );

        Ok(CallToolResult::success(vec![Content::text(output)]))
    }

    /// List published posts
    #[tool(description = "List published micropub posts with pagination")]
    async fn list_posts(
        &self,
        Parameters(args): Parameters<ListPostsArgs>,
    ) -> Result<CallToolResult, McpError> {
        let posts = crate::operations::fetch_posts(args.limit, args.offset)
            .await
            .map_err(|e| {
                McpError::new(
                    ErrorCode::INTERNAL_ERROR,
                    format!("Failed to fetch posts: {}", e),
                    None,
                )
            })?;

        if posts.is_empty() {
            return Ok(CallToolResult::success(vec![Content::text(
                "No posts found.",
            )]));
        }

        let mut output = String::from("Posts:\n\n");
        for post in posts {
            let title = post.name.unwrap_or_else(|| "[untitled]".to_string());
            output.push_str(&format!("- {} ({})\n", title, post.url));
            output.push_str(&format!("  Published: {}\n", post.published));
            if !post.categories.is_empty() {
                output.push_str(&format!("  Categories: {}\n", post.categories.join(", ")));
            }
            if !post.content.is_empty() {
                let preview = if post.content.len() > 100 {
                    format!("{}...", &post.content[..100])
                } else {
                    post.content.clone()
                };
                output.push_str(&format!("  Preview: {}\n", preview));
            }
            output.push('\n');
        }

        Ok(CallToolResult::success(vec![Content::text(output)]))
    }

    /// View a specific draft
    #[tool(description = "View the content of a specific draft")]
    async fn view_draft(
        &self,
        Parameters(args): Parameters<ViewDraftArgs>,
    ) -> Result<CallToolResult, McpError> {
        // Validate draft_id format to prevent path traversal
        validate_draft_id(&args.draft_id)
            .map_err(|e| McpError::invalid_params(format!("Invalid draft ID: {}", e), None))?;

        let draft = Draft::load(&args.draft_id)
            .map_err(|e| McpError::invalid_params(format!("Failed to load draft: {}", e), None))?;

        let mut output = String::new();
        output.push_str(&format!("Draft: {}\n\n", args.draft_id));

        if let Some(ref title) = draft.metadata.name {
            output.push_str(&format!("Title: {}\n", title));
        }
        if !draft.metadata.category.is_empty() {
            output.push_str(&format!(
                "Categories: {}\n",
                draft.metadata.category.join(", ")
            ));
        }
        output.push_str(&format!("\nContent:\n{}", draft.content));

        Ok(CallToolResult::success(vec![Content::text(output)]))
    }

    /// List media files
    #[tool(description = "List uploaded media files with pagination")]
    async fn list_media(
        &self,
        Parameters(args): Parameters<ListMediaArgs>,
    ) -> Result<CallToolResult, McpError> {
        let media_items = crate::operations::fetch_media(args.limit, args.offset)
            .await
            .map_err(|e| {
                McpError::new(
                    ErrorCode::INTERNAL_ERROR,
                    format!("Failed to fetch media: {}", e),
                    None,
                )
            })?;

        if media_items.is_empty() {
            return Ok(CallToolResult::success(vec![Content::text(
                "No media files found.",
            )]));
        }

        let mut output = String::from("Media files:\n\n");
        for item in media_items {
            output.push_str(&format!("- {}\n", item.url));
            if let Some(ref name) = item.name {
                output.push_str(&format!("  Name: {}\n", name));
            }
            output.push_str(&format!("  Uploaded: {}\n\n", item.uploaded));
        }

        Ok(CallToolResult::success(vec![Content::text(output)]))
    }

    /// Upload a media file to the micropub media endpoint
    #[tool(
        description = "Upload an image or media file to your micropub site. Supports local file paths (e.g., ~/Pictures/photo.jpg) or base64-encoded data. Returns URL and markdown snippet for use in posts."
    )]
    async fn upload_media(
        &self,
        Parameters(args): Parameters<UploadMediaArgs>,
    ) -> Result<CallToolResult, McpError> {
        // Validate: must have file_path OR (file_data + filename)
        let has_path = args.file_path.is_some();
        let has_data = args.file_data.is_some();
        let has_filename = args.filename.is_some();

        if !has_path && !has_data {
            return Err(McpError::invalid_params(
                "Must provide either file_path OR file_data".to_string(),
                None,
            ));
        }

        if has_path && has_data {
            return Err(McpError::invalid_params(
                "Cannot provide both file_path and file_data".to_string(),
                None,
            ));
        }

        if has_data && !has_filename {
            return Err(McpError::invalid_params(
                "filename is required when using file_data".to_string(),
                None,
            ));
        }

        // Get config and profile
        let config = Config::load().map_err(|e| {
            McpError::new(
                ErrorCode::INTERNAL_ERROR,
                format!("Failed to load config: {}", e),
                None,
            )
        })?;

        let profile_name = &config.default_profile;
        if profile_name.is_empty() {
            return Err(McpError::new(
                ErrorCode::INTERNAL_ERROR,
                "No profile configured. Run 'micropub auth <domain>' first.".to_string(),
                None,
            ));
        }

        let profile = config.get_profile(profile_name).ok_or_else(|| {
            McpError::new(
                ErrorCode::INTERNAL_ERROR,
                "Profile not found".to_string(),
                None,
            )
        })?;

        let media_endpoint = profile.media_endpoint.as_ref().ok_or_else(|| {
            McpError::new(
                ErrorCode::INTERNAL_ERROR,
                "No media endpoint configured. Server may not support media uploads.".to_string(),
                None,
            )
        })?;

        let token = crate::config::load_token(profile_name).map_err(|e| {
            McpError::new(
                ErrorCode::INTERNAL_ERROR,
                format!("Failed to load token: {}", e),
                None,
            )
        })?;

        // Handle file_path upload
        let (url, filename_str, mime_type) = if let Some(file_path) = args.file_path {
            let resolved_path = crate::media::resolve_path(&file_path, None)
                .map_err(|e| McpError::invalid_params(format!("Invalid file path: {}", e), None))?;

            let filename = resolved_path
                .file_name()
                .and_then(|n| n.to_str())
                .ok_or_else(|| McpError::invalid_params("Invalid filename".to_string(), None))?
                .to_string();

            let mime = mime_guess::from_path(&resolved_path).first_or_octet_stream();

            let url = crate::media::upload_file(media_endpoint, &token, &resolved_path)
                .await
                .map_err(|e| {
                    McpError::new(
                        ErrorCode::INTERNAL_ERROR,
                        format!("Upload failed: {}", e),
                        None,
                    )
                })?;

            (url, filename, mime.to_string())
        } else if let Some(file_data) = args.file_data {
            let filename = args.filename.unwrap(); // Already validated above

            // Decode base64
            let decoded = general_purpose::STANDARD.decode(&file_data).map_err(|e| {
                McpError::invalid_params(format!("Invalid base64 data: {}", e), None)
            })?;

            // Write to temp file
            let temp_dir = std::env::temp_dir();
            let temp_path = temp_dir.join(&filename);

            std::fs::write(&temp_path, decoded).map_err(|e| {
                McpError::new(
                    ErrorCode::INTERNAL_ERROR,
                    format!("Failed to write temp file: {}", e),
                    None,
                )
            })?;

            let mime = mime_guess::from_path(&temp_path).first_or_octet_stream();

            let url = crate::media::upload_file(media_endpoint, &token, &temp_path)
                .await
                .map_err(|e| {
                    // Clean up temp file
                    let _ = std::fs::remove_file(&temp_path);
                    McpError::new(
                        ErrorCode::INTERNAL_ERROR,
                        format!("Upload failed: {}", e),
                        None,
                    )
                })?;

            // Clean up temp file
            let _ = std::fs::remove_file(&temp_path);

            (url, filename, mime.to_string())
        } else {
            unreachable!("Validation ensures file_path or file_data is present");
        };

        // Build response
        let alt_text = args.alt_text.unwrap_or_default();
        let markdown = if alt_text.is_empty() {
            format!("![]({})", url)
        } else {
            format!("![{}]({})", alt_text, url)
        };

        let response = serde_json::json!({
            "url": url,
            "filename": filename_str,
            "mime_type": mime_type,
            "markdown": markdown
        });

        Ok(CallToolResult::success(vec![Content::text(
            serde_json::to_string_pretty(&response).unwrap_or_else(|_| response.to_string()),
        )]))
    }

    /// Push a local draft to the server as a server-side draft
    #[tool(
        description = "Push a local draft to the server as a server-side draft (post-status: draft). Uploads any media files and returns the server URL. Can be used to create new server drafts or update existing ones. Supports backdating."
    )]
    async fn push_draft(
        &self,
        Parameters(args): Parameters<PushDraftArgs>,
    ) -> Result<CallToolResult, McpError> {
        // Validate draft_id format to prevent path traversal
        validate_draft_id(&args.draft_id)
            .map_err(|e| McpError::invalid_params(format!("Invalid draft ID: {}", e), None))?;

        // Parse backdate if provided
        let backdate_parsed = if let Some(date_str) = args.backdate {
            let parsed = DateTime::parse_from_rfc3339(&date_str)
                .map_err(|e| {
                    McpError::invalid_params(
                        format!(
                            "Invalid backdate format: {}. Use ISO 8601 like 2024-01-15T10:30:00Z",
                            e
                        ),
                        None,
                    )
                })?
                .with_timezone(&Utc);
            Some(parsed)
        } else {
            None
        };

        // Push draft to server
        let result = crate::draft_push::cmd_push_draft(&args.draft_id, backdate_parsed)
            .await
            .map_err(|e| {
                McpError::new(
                    ErrorCode::INTERNAL_ERROR,
                    format!("Failed to push draft: {}", e),
                    None,
                )
            })?;

        // Build response JSON
        let response = serde_json::json!({
            "url": result.url,
            "is_update": result.is_update,
            "status": "server-draft",
            "uploaded_media": result.uploads.iter().map(|(filename, url)| {
                serde_json::json!({
                    "filename": filename,
                    "url": url
                })
            }).collect::<Vec<_>>()
        });

        Ok(CallToolResult::success(vec![Content::text(
            serde_json::to_string_pretty(&response).unwrap_or_else(|_| response.to_string()),
        )]))
    }
}

/// Prompts for common micropub workflows
#[prompt_router]
impl MicropubMcp {
    /// Template for posting a quick note or thought
    #[prompt(
        name = "quick-note",
        description = "Post a quick note or thought to your micropub site"
    )]
    async fn quick_note(
        &self,
        Parameters(args): Parameters<QuickNotePromptArgs>,
    ) -> Result<GetPromptResult, McpError> {
        // Validate and normalize topic
        let topic = args.topic.trim();
        if topic.is_empty() {
            return Err(McpError::invalid_params(
                "Topic cannot be empty".to_string(),
                None,
            ));
        }

        Ok(GetPromptResult {
            description: Some("Quick note posting workflow".to_string()),
            messages: vec![
                PromptMessage::new_text(
                    PromptMessageRole::User,
                    format!("I want to post a quick note about: {}", topic),
                ),
                PromptMessage::new_text(
                    PromptMessageRole::Assistant,
                    format!(
                        "I'll help you create a quick note about {}. What would you like to say?",
                        topic
                    ),
                ),
            ],
        })
    }

    /// Template for posting a photo with caption
    #[prompt(
        name = "photo-post",
        description = "Create a photo post with caption for your micropub site"
    )]
    async fn photo_post(
        &self,
        Parameters(args): Parameters<PhotoPostPromptArgs>,
    ) -> Result<GetPromptResult, McpError> {
        // Validate and normalize subject
        let subject = args.subject.trim();
        if subject.is_empty() {
            return Err(McpError::invalid_params(
                "Subject cannot be empty".to_string(),
                None,
            ));
        }

        Ok(GetPromptResult {
            description: Some("Photo post workflow".to_string()),
            messages: vec![
                PromptMessage::new_text(
                    PromptMessageRole::User,
                    format!("I want to post a photo about: {}", subject),
                ),
                PromptMessage::new_text(
                    PromptMessageRole::Assistant,
                    format!(
                        "I'll help you create a photo post about {}. You can:\n\
                         1. Upload the image first with 'upload_media' tool, then use the URL\n\
                         2. Reference a local file (e.g., ~/Pictures/photo.jpg) and I'll auto-upload when publishing\n\n\
                         Please provide the photo path and a caption.",
                        subject
                    ),
                ),
            ],
        })
    }

    /// Template for creating a longer article draft
    #[prompt(
        name = "article-draft",
        description = "Create a longer article draft for later editing and publishing"
    )]
    async fn article_draft(
        &self,
        Parameters(args): Parameters<ArticleDraftPromptArgs>,
    ) -> Result<GetPromptResult, McpError> {
        // Validate and normalize topic
        let topic = args.topic.trim();
        if topic.is_empty() {
            return Err(McpError::invalid_params(
                "Topic cannot be empty".to_string(),
                None,
            ));
        }

        // Validate and normalize key_points if provided
        let key_points = args.key_points.as_ref().map(|p| p.trim());
        if let Some(points) = key_points {
            if points.is_empty() {
                return Err(McpError::invalid_params(
                    "Key points cannot be empty if provided".to_string(),
                    None,
                ));
            }
        }

        let key_points_text = if let Some(points) = key_points {
            format!("\n\nKey points to cover:\n{}", points)
        } else {
            String::new()
        };

        Ok(GetPromptResult {
            description: Some("Article draft creation workflow".to_string()),
            messages: vec![
                PromptMessage::new_text(
                    PromptMessageRole::User,
                    format!(
                        "I want to write an article about: {}{}",
                        topic, key_points_text
                    ),
                ),
                PromptMessage::new_text(
                    PromptMessageRole::Assistant,
                    format!(
                        "I'll help you draft an article about {}. Let's start with:\n\
                         1. A compelling title\n\
                         2. An introduction that hooks the reader\n\
                         3. Main body sections{}\n\
                         4. A conclusion\n\n\
                         This will be saved as a draft for you to edit before publishing.",
                        topic,
                        if key_points.is_some() {
                            " covering your key points"
                        } else {
                            ""
                        }
                    ),
                ),
            ],
        })
    }

    /// Template for backdating a memory or past event
    #[prompt(
        name = "backdate-memory",
        description = "Record a memory or past event with its original date"
    )]
    async fn backdate_memory(
        &self,
        Parameters(args): Parameters<BackdateMemoryPromptArgs>,
    ) -> Result<GetPromptResult, McpError> {
        // Validate and normalize memory
        let memory = args.memory.trim();
        if memory.is_empty() {
            return Err(McpError::invalid_params(
                "Memory cannot be empty".to_string(),
                None,
            ));
        }

        // Validate and normalize when
        let when = args.when.trim();
        if when.is_empty() {
            return Err(McpError::invalid_params(
                "When cannot be empty".to_string(),
                None,
            ));
        }

        Ok(GetPromptResult {
            description: Some("Backdated memory recording workflow".to_string()),
            messages: vec![
                PromptMessage::new_text(
                    PromptMessageRole::User,
                    format!("I want to record this memory from {}: {}", when, memory),
                ),
                PromptMessage::new_text(
                    PromptMessageRole::Assistant,
                    format!(
                        "I'll help you record this memory from {}. Let's:\n\
                         1. Write out the full memory in detail\n\
                         2. Convert '{}' to a specific date (ISO 8601 format)\n\
                         3. Save it as a draft\n\
                         4. Publish it with the backdated timestamp\n\n\
                         Tell me more about what happened.",
                        when, when
                    ),
                ),
            ],
        })
    }

    /// Template for creating a categorized post
    #[prompt(
        name = "categorized-post",
        description = "Create a post with specific categories for organization"
    )]
    async fn categorized_post(
        &self,
        Parameters(args): Parameters<CategorizedPostPromptArgs>,
    ) -> Result<GetPromptResult, McpError> {
        // Validate and normalize topic
        let topic = args.topic.trim();
        if topic.is_empty() {
            return Err(McpError::invalid_params(
                "Topic cannot be empty".to_string(),
                None,
            ));
        }

        // Validate and normalize categories
        let categories = args.categories.trim();
        if categories.is_empty() {
            return Err(McpError::invalid_params(
                "Categories cannot be empty".to_string(),
                None,
            ));
        }

        Ok(GetPromptResult {
            description: Some("Categorized post workflow".to_string()),
            messages: vec![
                PromptMessage::new_text(
                    PromptMessageRole::User,
                    format!(
                        "I want to post about {} in categories: {}",
                        topic, categories
                    ),
                ),
                PromptMessage::new_text(
                    PromptMessageRole::Assistant,
                    format!(
                        "I'll help you create a post about {} with categories: {}.\n\n\
                         What would you like to say? I'll make sure to tag it appropriately.",
                        topic, categories
                    ),
                ),
            ],
        })
    }

    /// General micropub posting workflow
    #[prompt(
        name = "new-post",
        description = "General workflow for creating a new micropub post"
    )]
    async fn new_post(&self) -> GetPromptResult {
        GetPromptResult {
            description: Some("General micropub posting workflow".to_string()),
            messages: vec![
                PromptMessage::new_text(
                    PromptMessageRole::User,
                    "I want to create a new post".to_string(),
                ),
                PromptMessage::new_text(
                    PromptMessageRole::Assistant,
                    "I'll help you create a new micropub post! What type of post would you like to make?\n\n\
                     - Quick note or thought\n\
                     - Photo with caption\n\
                     - Longer article (saved as draft)\n\
                     - Backdated memory\n\
                     - Categorized post\n\n\
                     Or just tell me what you want to post and I'll figure out the best format!".to_string(),
                ),
            ],
        }
    }
}

/// Implement ServerHandler to provide server metadata
#[tool_handler]
#[prompt_handler(router = self.prompt_router)]
impl ServerHandler for MicropubMcp {
    fn get_info(&self) -> ServerInfo {
        ServerInfo {
            protocol_version: ProtocolVersion::V_2024_11_05,
            capabilities: ServerCapabilities::builder()
                .enable_tools()
                .enable_prompts()
                .build(),
            server_info: Implementation::from_build_env(),
            instructions: Some(
                "Micropub MCP server for posting and managing micropub content via AI assistants.\n\n\
                 IMAGE UPLOADS:\n\
                 - Use 'upload_media' tool to upload images explicitly (supports file paths or base64 data)\n\
                 - Or use 'publish_post' with local image paths (e.g., ![alt](~/photo.jpg)) - they'll auto-upload\n\n\
                 SERVER-SIDE DRAFTS:\n\
                 - Use 'push_draft' tool to save drafts to server with post-status: draft\n\
                 - Drafts remain editable locally and can be re-pushed to update\n\
                 - Use 'publish_post' to change server draft to published status\n\
                 - Supports media upload and backdating when pushing drafts\n\n\
                 All uploads and draft operations require authentication via 'micropub auth <domain>' first."
                    .to_string(),
            ),
        }
    }
}

/// Run the MCP server
pub async fn run_server() -> Result<()> {
    eprintln!("Starting Micropub MCP server...");
    eprintln!("Ready to receive requests via stdio");

    // Create server and serve via stdio
    let service = MicropubMcp::new()?.serve(stdio()).await?;

    // Wait for shutdown
    service.waiting().await?;

    Ok(())
}