mcpcn-office-powerpoint-mcp-server 2.0.7__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
tools/content_tools.py ADDED
@@ -0,0 +1,593 @@
1
+ """
2
+ Content management tools for PowerPoint MCP Server.
3
+ Handles slides, text, images, and content manipulation.
4
+ """
5
+ from typing import Dict, List, Optional, Any, Union
6
+ from mcp.server.fastmcp import FastMCP
7
+ import utils as ppt_utils
8
+ import tempfile
9
+ import base64
10
+ import os
11
+
12
+
13
+ def register_content_tools(app: FastMCP, presentations: Dict, get_current_presentation_id, validate_parameters, is_positive, is_non_negative, is_in_range, is_valid_rgb):
14
+ """Register content management tools with the FastMCP app"""
15
+
16
+ @app.tool()
17
+ def add_slide(
18
+ layout_index: int = 1,
19
+ title: Optional[str] = None,
20
+ background_type: Optional[str] = None, # "solid", "gradient", "professional_gradient"
21
+ background_colors: Optional[List[List[int]]] = None, # For gradient: [[start_rgb], [end_rgb]]
22
+ gradient_direction: str = "horizontal",
23
+ color_scheme: str = "modern_blue",
24
+ presentation_id: Optional[str] = None
25
+ ) -> Dict:
26
+ """Add a new slide to the presentation with optional background styling."""
27
+ pres_id = presentation_id if presentation_id is not None else get_current_presentation_id()
28
+
29
+ if pres_id is None or pres_id not in presentations:
30
+ return {
31
+ "error": "No presentation is currently loaded or the specified ID is invalid"
32
+ }
33
+
34
+ pres = presentations[pres_id]
35
+
36
+ # Validate layout index
37
+ if layout_index < 0 or layout_index >= len(pres.slide_layouts):
38
+ return {
39
+ "error": f"Invalid layout index: {layout_index}. Available layouts: 0-{len(pres.slide_layouts) - 1}"
40
+ }
41
+
42
+ try:
43
+ # Add the slide
44
+ slide, layout = ppt_utils.add_slide(pres, layout_index)
45
+ slide_index = len(pres.slides) - 1
46
+
47
+ # Set title if provided
48
+ if title:
49
+ ppt_utils.set_title(slide, title)
50
+
51
+ # Apply background if specified
52
+ if background_type == "gradient" and background_colors and len(background_colors) >= 2:
53
+ ppt_utils.set_slide_gradient_background(
54
+ slide, background_colors[0], background_colors[1], gradient_direction
55
+ )
56
+ elif background_type == "professional_gradient":
57
+ ppt_utils.create_professional_gradient_background(
58
+ slide, color_scheme, "subtle", gradient_direction
59
+ )
60
+
61
+ return {
62
+ "message": f"Added slide {slide_index} with layout {layout_index}",
63
+ "slide_index": slide_index,
64
+ "layout_name": layout.name if hasattr(layout, 'name') else f"Layout {layout_index}"
65
+ }
66
+ except Exception as e:
67
+ return {
68
+ "error": f"Failed to add slide: {str(e)}"
69
+ }
70
+
71
+ @app.tool()
72
+ def get_slide_info(slide_index: int, presentation_id: Optional[str] = None) -> Dict:
73
+ """Get information about a specific slide."""
74
+ pres_id = presentation_id if presentation_id is not None else get_current_presentation_id()
75
+
76
+ if pres_id is None or pres_id not in presentations:
77
+ return {
78
+ "error": "No presentation is currently loaded or the specified ID is invalid"
79
+ }
80
+
81
+ pres = presentations[pres_id]
82
+
83
+ if slide_index < 0 or slide_index >= len(pres.slides):
84
+ return {
85
+ "error": f"Invalid slide index: {slide_index}. Available slides: 0-{len(pres.slides) - 1}"
86
+ }
87
+
88
+ slide = pres.slides[slide_index]
89
+
90
+ try:
91
+ return ppt_utils.get_slide_info(slide, slide_index)
92
+ except Exception as e:
93
+ return {
94
+ "error": f"Failed to get slide info: {str(e)}"
95
+ }
96
+
97
+ @app.tool()
98
+ def extract_slide_text(slide_index: int, presentation_id: Optional[str] = None) -> Dict:
99
+ """Extract all text content from a specific slide."""
100
+ pres_id = presentation_id if presentation_id is not None else get_current_presentation_id()
101
+
102
+ if pres_id is None or pres_id not in presentations:
103
+ return {
104
+ "error": "No presentation is currently loaded or the specified ID is invalid"
105
+ }
106
+
107
+ pres = presentations[pres_id]
108
+
109
+ if slide_index < 0 or slide_index >= len(pres.slides):
110
+ return {
111
+ "error": f"Invalid slide index: {slide_index}. Available slides: 0-{len(pres.slides) - 1}"
112
+ }
113
+
114
+ slide = pres.slides[slide_index]
115
+
116
+ try:
117
+ result = ppt_utils.extract_slide_text_content(slide)
118
+ result["slide_index"] = slide_index
119
+ return result
120
+ except Exception as e:
121
+ return {
122
+ "error": f"Failed to extract slide text: {str(e)}"
123
+ }
124
+
125
+ @app.tool()
126
+ def extract_presentation_text(presentation_id: Optional[str] = None, include_slide_info: bool = True) -> Dict:
127
+ """Extract all text content from all slides in the presentation."""
128
+ pres_id = presentation_id if presentation_id is not None else get_current_presentation_id()
129
+
130
+ if pres_id is None or pres_id not in presentations:
131
+ return {
132
+ "error": "No presentation is currently loaded or the specified ID is invalid"
133
+ }
134
+
135
+ pres = presentations[pres_id]
136
+
137
+ try:
138
+ slides_text = []
139
+ total_text_shapes = 0
140
+ slides_with_tables = 0
141
+ slides_with_titles = 0
142
+ all_presentation_text = []
143
+
144
+ for slide_index, slide in enumerate(pres.slides):
145
+ slide_text_result = ppt_utils.extract_slide_text_content(slide)
146
+
147
+ if slide_text_result["success"]:
148
+ slide_data = {
149
+ "slide_index": slide_index,
150
+ "text_content": slide_text_result["text_content"]
151
+ }
152
+
153
+ if include_slide_info:
154
+ # Add basic slide info
155
+ slide_data["layout_name"] = slide.slide_layout.name
156
+ slide_data["total_text_shapes"] = slide_text_result["total_text_shapes"]
157
+ slide_data["has_title"] = slide_text_result["has_title"]
158
+ slide_data["has_tables"] = slide_text_result["has_tables"]
159
+
160
+ slides_text.append(slide_data)
161
+
162
+ # Accumulate statistics
163
+ total_text_shapes += slide_text_result["total_text_shapes"]
164
+ if slide_text_result["has_tables"]:
165
+ slides_with_tables += 1
166
+ if slide_text_result["has_title"]:
167
+ slides_with_titles += 1
168
+
169
+ # Collect all text for combined output
170
+ if slide_text_result["text_content"]["all_text_combined"]:
171
+ all_presentation_text.append(f"=== SLIDE {slide_index + 1} ===")
172
+ all_presentation_text.append(slide_text_result["text_content"]["all_text_combined"])
173
+ all_presentation_text.append("") # Empty line separator
174
+ else:
175
+ slides_text.append({
176
+ "slide_index": slide_index,
177
+ "error": slide_text_result.get("error", "Unknown error"),
178
+ "text_content": None
179
+ })
180
+
181
+ return {
182
+ "success": True,
183
+ "presentation_id": pres_id,
184
+ "total_slides": len(pres.slides),
185
+ "slides_with_text": len([s for s in slides_text if s.get("text_content") is not None]),
186
+ "total_text_shapes": total_text_shapes,
187
+ "slides_with_titles": slides_with_titles,
188
+ "slides_with_tables": slides_with_tables,
189
+ "slides_text": slides_text,
190
+ "all_presentation_text_combined": "\n".join(all_presentation_text)
191
+ }
192
+
193
+ except Exception as e:
194
+ return {
195
+ "error": f"Failed to extract presentation text: {str(e)}"
196
+ }
197
+
198
+ @app.tool()
199
+ def populate_placeholder(
200
+ slide_index: int,
201
+ placeholder_idx: int,
202
+ text: str,
203
+ presentation_id: Optional[str] = None
204
+ ) -> Dict:
205
+ """Populate a placeholder with text."""
206
+ pres_id = presentation_id if presentation_id is not None else get_current_presentation_id()
207
+
208
+ if pres_id is None or pres_id not in presentations:
209
+ return {
210
+ "error": "No presentation is currently loaded or the specified ID is invalid"
211
+ }
212
+
213
+ pres = presentations[pres_id]
214
+
215
+ if slide_index < 0 or slide_index >= len(pres.slides):
216
+ return {
217
+ "error": f"Invalid slide index: {slide_index}. Available slides: 0-{len(pres.slides) - 1}"
218
+ }
219
+
220
+ slide = pres.slides[slide_index]
221
+
222
+ try:
223
+ ppt_utils.populate_placeholder(slide, placeholder_idx, text)
224
+ return {
225
+ "message": f"Populated placeholder {placeholder_idx} on slide {slide_index}"
226
+ }
227
+ except Exception as e:
228
+ return {
229
+ "error": f"Failed to populate placeholder: {str(e)}"
230
+ }
231
+
232
+ @app.tool()
233
+ def add_bullet_points(
234
+ slide_index: int,
235
+ placeholder_idx: int,
236
+ bullet_points: List[str],
237
+ presentation_id: Optional[str] = None
238
+ ) -> Dict:
239
+ """Add bullet points to a placeholder."""
240
+ pres_id = presentation_id if presentation_id is not None else get_current_presentation_id()
241
+
242
+ if pres_id is None or pres_id not in presentations:
243
+ return {
244
+ "error": "No presentation is currently loaded or the specified ID is invalid"
245
+ }
246
+
247
+ pres = presentations[pres_id]
248
+
249
+ if slide_index < 0 or slide_index >= len(pres.slides):
250
+ return {
251
+ "error": f"Invalid slide index: {slide_index}. Available slides: 0-{len(pres.slides) - 1}"
252
+ }
253
+
254
+ slide = pres.slides[slide_index]
255
+
256
+ try:
257
+ placeholder = slide.placeholders[placeholder_idx]
258
+ ppt_utils.add_bullet_points(placeholder, bullet_points)
259
+ return {
260
+ "message": f"Added {len(bullet_points)} bullet points to placeholder {placeholder_idx} on slide {slide_index}"
261
+ }
262
+ except Exception as e:
263
+ return {
264
+ "error": f"Failed to add bullet points: {str(e)}"
265
+ }
266
+
267
+ @app.tool()
268
+ def manage_text(
269
+ slide_index: int,
270
+ operation: str, # "add", "format", "validate", "format_runs"
271
+ left: float = 1.0,
272
+ top: float = 1.0,
273
+ width: float = 4.0,
274
+ height: float = 2.0,
275
+ text: str = "",
276
+ shape_index: Optional[int] = None, # For format/validate operations
277
+ text_runs: Optional[List[Dict]] = None, # For format_runs operation
278
+ # Formatting options
279
+ font_size: Optional[int] = None,
280
+ font_name: Optional[str] = None,
281
+ bold: Optional[bool] = None,
282
+ italic: Optional[bool] = None,
283
+ underline: Optional[bool] = None,
284
+ color: Optional[List[int]] = None,
285
+ bg_color: Optional[List[int]] = None,
286
+ alignment: Optional[str] = None,
287
+ vertical_alignment: Optional[str] = None,
288
+ # Advanced options
289
+ auto_fit: bool = True,
290
+ validation_only: bool = False,
291
+ min_font_size: int = 8,
292
+ max_font_size: int = 72,
293
+ presentation_id: Optional[str] = None
294
+ ) -> Dict:
295
+ """Unified text management tool for adding, formatting, validating text, and formatting multiple text runs."""
296
+ pres_id = presentation_id if presentation_id is not None else get_current_presentation_id()
297
+
298
+ if pres_id is None or pres_id not in presentations:
299
+ return {
300
+ "error": "No presentation is currently loaded or the specified ID is invalid"
301
+ }
302
+
303
+ pres = presentations[pres_id]
304
+
305
+ if slide_index < 0 or slide_index >= len(pres.slides):
306
+ return {
307
+ "error": f"Invalid slide index: {slide_index}. Available slides: 0-{len(pres.slides) - 1}"
308
+ }
309
+
310
+ slide = pres.slides[slide_index]
311
+
312
+ # Validate parameters
313
+ validations = {}
314
+ if font_size is not None:
315
+ validations["font_size"] = (font_size, [(is_positive, "must be a positive integer")])
316
+ if color is not None:
317
+ validations["color"] = (color, [(is_valid_rgb, "must be a valid RGB list [R, G, B] with values 0-255")])
318
+ if bg_color is not None:
319
+ validations["bg_color"] = (bg_color, [(is_valid_rgb, "must be a valid RGB list [R, G, B] with values 0-255")])
320
+
321
+ if validations:
322
+ valid, error = validate_parameters(validations)
323
+ if not valid:
324
+ return {"error": error}
325
+
326
+ try:
327
+ if operation == "add":
328
+ # Add new textbox
329
+ shape = ppt_utils.add_textbox(
330
+ slide, left, top, width, height, text,
331
+ font_size=font_size,
332
+ font_name=font_name,
333
+ bold=bold,
334
+ italic=italic,
335
+ underline=underline,
336
+ color=tuple(color) if color else None,
337
+ bg_color=tuple(bg_color) if bg_color else None,
338
+ alignment=alignment,
339
+ vertical_alignment=vertical_alignment,
340
+ auto_fit=auto_fit
341
+ )
342
+ return {
343
+ "message": f"Added text box to slide {slide_index}",
344
+ "shape_index": len(slide.shapes) - 1,
345
+ "text": text
346
+ }
347
+
348
+ elif operation == "format":
349
+ # Format existing text shape
350
+ if shape_index is None or shape_index < 0 or shape_index >= len(slide.shapes):
351
+ return {
352
+ "error": f"Invalid shape index for formatting: {shape_index}. Available shapes: 0-{len(slide.shapes) - 1}"
353
+ }
354
+
355
+ shape = slide.shapes[shape_index]
356
+ ppt_utils.format_text_advanced(
357
+ shape,
358
+ font_size=font_size,
359
+ font_name=font_name,
360
+ bold=bold,
361
+ italic=italic,
362
+ underline=underline,
363
+ color=tuple(color) if color else None,
364
+ bg_color=tuple(bg_color) if bg_color else None,
365
+ alignment=alignment,
366
+ vertical_alignment=vertical_alignment
367
+ )
368
+ return {
369
+ "message": f"Formatted text shape {shape_index} on slide {slide_index}"
370
+ }
371
+
372
+ elif operation == "validate":
373
+ # Validate text fit
374
+ if shape_index is None or shape_index < 0 or shape_index >= len(slide.shapes):
375
+ return {
376
+ "error": f"Invalid shape index for validation: {shape_index}. Available shapes: 0-{len(slide.shapes) - 1}"
377
+ }
378
+
379
+ validation_result = ppt_utils.validate_text_fit(
380
+ slide.shapes[shape_index],
381
+ text_content=text or None,
382
+ font_size=font_size or 12
383
+ )
384
+
385
+ if not validation_only and validation_result.get("needs_optimization"):
386
+ # Apply automatic fixes
387
+ fix_result = ppt_utils.validate_and_fix_slide(
388
+ slide,
389
+ auto_fix=True,
390
+ min_font_size=min_font_size,
391
+ max_font_size=max_font_size
392
+ )
393
+ validation_result.update(fix_result)
394
+
395
+ return validation_result
396
+
397
+ elif operation == "format_runs":
398
+ # Format multiple text runs with different formatting
399
+ if shape_index is None or shape_index < 0 or shape_index >= len(slide.shapes):
400
+ return {
401
+ "error": f"Invalid shape index for format_runs: {shape_index}. Available shapes: 0-{len(slide.shapes) - 1}"
402
+ }
403
+
404
+ if not text_runs:
405
+ return {"error": "text_runs parameter is required for format_runs operation"}
406
+
407
+ shape = slide.shapes[shape_index]
408
+
409
+ # Check if shape has text
410
+ if not hasattr(shape, 'text_frame') or not shape.text_frame:
411
+ return {"error": "Shape does not contain text"}
412
+
413
+ # Clear existing text and rebuild with formatted runs
414
+ text_frame = shape.text_frame
415
+ text_frame.clear()
416
+
417
+ formatted_runs = []
418
+
419
+ for run_data in text_runs:
420
+ if 'text' not in run_data:
421
+ continue
422
+
423
+ # Add paragraph if needed
424
+ if not text_frame.paragraphs:
425
+ paragraph = text_frame.paragraphs[0]
426
+ else:
427
+ paragraph = text_frame.add_paragraph()
428
+
429
+ # Add run with text
430
+ run = paragraph.add_run()
431
+ run.text = run_data['text']
432
+
433
+ # Apply formatting using pptx imports
434
+ from pptx.util import Pt
435
+ from pptx.dml.color import RGBColor
436
+
437
+ if 'bold' in run_data:
438
+ run.font.bold = run_data['bold']
439
+ if 'italic' in run_data:
440
+ run.font.italic = run_data['italic']
441
+ if 'underline' in run_data:
442
+ run.font.underline = run_data['underline']
443
+ if 'font_size' in run_data:
444
+ run.font.size = Pt(run_data['font_size'])
445
+ if 'font_name' in run_data:
446
+ run.font.name = run_data['font_name']
447
+ if 'color' in run_data and is_valid_rgb(run_data['color']):
448
+ run.font.color.rgb = RGBColor(*run_data['color'])
449
+ if 'hyperlink' in run_data:
450
+ run.hyperlink.address = run_data['hyperlink']
451
+
452
+ formatted_runs.append({
453
+ "text": run_data['text'],
454
+ "formatting_applied": {k: v for k, v in run_data.items() if k != 'text'}
455
+ })
456
+
457
+ return {
458
+ "message": f"Applied formatting to {len(formatted_runs)} text runs on shape {shape_index}",
459
+ "slide_index": slide_index,
460
+ "shape_index": shape_index,
461
+ "formatted_runs": formatted_runs
462
+ }
463
+
464
+ else:
465
+ return {
466
+ "error": f"Invalid operation: {operation}. Must be 'add', 'format', 'validate', or 'format_runs'"
467
+ }
468
+
469
+ except Exception as e:
470
+ return {
471
+ "error": f"Failed to {operation} text: {str(e)}"
472
+ }
473
+
474
+ @app.tool()
475
+ def manage_image(
476
+ slide_index: int,
477
+ operation: str, # "add", "enhance"
478
+ image_source: str, # file path or base64 string
479
+ source_type: str = "file", # "file" or "base64"
480
+ left: float = 1.0,
481
+ top: float = 1.0,
482
+ width: Optional[float] = None,
483
+ height: Optional[float] = None,
484
+ # Enhancement options
485
+ enhancement_style: Optional[str] = None, # "presentation", "custom"
486
+ brightness: float = 1.0,
487
+ contrast: float = 1.0,
488
+ saturation: float = 1.0,
489
+ sharpness: float = 1.0,
490
+ blur_radius: float = 0,
491
+ filter_type: Optional[str] = None,
492
+ output_path: Optional[str] = None,
493
+ presentation_id: Optional[str] = None
494
+ ) -> Dict:
495
+ """Unified image management tool for adding and enhancing images."""
496
+ pres_id = presentation_id if presentation_id is not None else get_current_presentation_id()
497
+
498
+ if pres_id is None or pres_id not in presentations:
499
+ return {
500
+ "error": "No presentation is currently loaded or the specified ID is invalid"
501
+ }
502
+
503
+ pres = presentations[pres_id]
504
+
505
+ if slide_index < 0 or slide_index >= len(pres.slides):
506
+ return {
507
+ "error": f"Invalid slide index: {slide_index}. Available slides: 0-{len(pres.slides) - 1}"
508
+ }
509
+
510
+ slide = pres.slides[slide_index]
511
+
512
+ try:
513
+ if operation == "add":
514
+ if source_type == "base64":
515
+ # Handle base64 image
516
+ try:
517
+ image_data = base64.b64decode(image_source)
518
+ with tempfile.NamedTemporaryFile(delete=False, suffix='.png') as temp_file:
519
+ temp_file.write(image_data)
520
+ temp_path = temp_file.name
521
+
522
+ # Add image from temporary file
523
+ shape = ppt_utils.add_image(slide, temp_path, left, top, width, height)
524
+
525
+ # Clean up temporary file
526
+ os.unlink(temp_path)
527
+
528
+ return {
529
+ "message": f"Added image from base64 to slide {slide_index}",
530
+ "shape_index": len(slide.shapes) - 1
531
+ }
532
+ except Exception as e:
533
+ return {
534
+ "error": f"Failed to process base64 image: {str(e)}"
535
+ }
536
+ else:
537
+ # Handle file path
538
+ if not os.path.exists(image_source):
539
+ return {
540
+ "error": f"Image file not found: {image_source}"
541
+ }
542
+
543
+ shape = ppt_utils.add_image(slide, image_source, left, top, width, height)
544
+ return {
545
+ "message": f"Added image to slide {slide_index}",
546
+ "shape_index": len(slide.shapes) - 1,
547
+ "image_path": image_source
548
+ }
549
+
550
+ elif operation == "enhance":
551
+ # Enhance existing image file
552
+ if source_type == "base64":
553
+ return {
554
+ "error": "Enhancement operation requires file path, not base64 data"
555
+ }
556
+
557
+ if not os.path.exists(image_source):
558
+ return {
559
+ "error": f"Image file not found: {image_source}"
560
+ }
561
+
562
+ if enhancement_style == "presentation":
563
+ # Apply professional enhancement
564
+ enhanced_path = ppt_utils.apply_professional_image_enhancement(
565
+ image_source, style="presentation", output_path=output_path
566
+ )
567
+ else:
568
+ # Apply custom enhancement
569
+ enhanced_path = ppt_utils.enhance_image_with_pillow(
570
+ image_source,
571
+ brightness=brightness,
572
+ contrast=contrast,
573
+ saturation=saturation,
574
+ sharpness=sharpness,
575
+ blur_radius=blur_radius,
576
+ filter_type=filter_type,
577
+ output_path=output_path
578
+ )
579
+
580
+ return {
581
+ "message": f"Enhanced image: {image_source}",
582
+ "enhanced_path": enhanced_path
583
+ }
584
+
585
+ else:
586
+ return {
587
+ "error": f"Invalid operation: {operation}. Must be 'add' or 'enhance'"
588
+ }
589
+
590
+ except Exception as e:
591
+ return {
592
+ "error": f"Failed to {operation} image: {str(e)}"
593
+ }